You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中转换列:为每行元素添加引号生成新列

在R语言中实现列元素加双引号并分隔的转换操作

示例数据

先构造你提供的示例数据集:

df <- data.frame(
  Column1 = c("a", "a, b", "a, b, c"),
  stringsAsFactors = FALSE
)

方法1:Base R 实现

通过字符串分割、元素处理和拼接完成转换:

# 生成新列Column2
df$Column2 <- sapply(strsplit(df$Column1, ", "), function(x) {
  paste0('"', x, '"', collapse = ", ")
})

# 查看转换结果
print(df)

方法2:Tidyverse 工具链实现

用dplyr的管道语法配合stringr处理字符串,代码更简洁直观:

library(dplyr)
library(stringr)

df <- df %>%
  mutate(Column2 = str_split(Column1, ", ") %>% 
           map_chr(~paste0('"', .x, '"', collapse = ", ")))

# 查看转换结果
print(df)

最终输出结果

两种方法都会得到如下转换后的数据集:

Column1          Column2
1       a            "a"
2    a, b       "a", "b"
3 a, b, c "a", "b", "c"

内容的提问来源于stack exchange,提问作者confusedindividual

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:01:17