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

使用R的dplyr将多列单元格多因子拆分至单列多行

多列拆分合并解决方案

示例数据

先构造一个和需求匹配的示例数据集:

library(tibble)
df <- tibble(
  ID = 1:3,
  OtherColumn = c("A", "B", "C"),
  Collaborations = c("John Doe, Jane Smith", "0", "Bob Brown"),
  `Mini Collaborations` = c("0", "Alice Lee", "Charlie Davis, Eve Wilson"),
  Subcontractors = c("Frank Moore", "Grace Hall, Henry Taylor", "0")
)

使用 dplyr + tidyr 实现

利用pivot_longer先把三列合并成一列,再拆分逗号分隔值,最后过滤掉0:

library(dplyr)
library(tidyr)

result_dplyr <- df %>%
  # 把目标三列转为长格式,保留其他所有列
  pivot_longer(
    cols = c(Collaborations, `Mini Collaborations`, Subcontractors),
    values_to = "temp_collab"
  ) %>%
  # 拆分逗号分隔的内容,自动展开为单独行(处理逗号后可能的空格)
  separate_rows(temp_collab, sep = ",\\s*") %>%
  # 移除值为0的行
  filter(temp_collab != "0") %>%
  # 重命名为最终的Collaborations列
  rename(Collaborations = temp_collab) %>%
  # 删掉临时生成的name列(可选,若不需要记录原列来源)
  select(-name)

使用 data.table 实现

用melt转长格式,再用tstrsplit拆分并展开:

library(data.table)

dt <- as.data.table(df)

result_dt <- dt %>%
  # 熔化为长格式,保留非目标列作为分组键
  melt(
    id.vars = setdiff(names(dt), c("Collaborations", "Mini Collaborations", "Subcontractors")),
    measure.vars = c("Collaborations", "Mini Collaborations", "Subcontractors"),
    value.name = "temp_collab"
  ) %>%
  # 拆分逗号分隔值,按原行的所有其他列分组展开
  .[, .(Collaborations = unlist(tstrsplit(temp_collab, ",\\s*"))), by = setdiff(names(.), c("temp_collab", "variable"))] %>%
  # 过滤掉0的行
  .[Collaborations != "0"]

注意事项

  • sep = ",\\s*"能兼容逗号后带空格或不带空格的情况,避免拆分出带空格的名称
  • 两种方法都会保留原数据中除目标三列外的所有列,确保每条合作者记录能关联到原工作记录的其他信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:47:38