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

R语言如何将多列分隔字符串按位置对应关系拆分为多行

R实现多列拆分后按位置对应拆行

示例数据

df <- data.frame(Column1=c("1", "2", "3"), 
  Column2=c("craft1-craft2-craft3", "craft4-craft5", "craft6-craft7"), 
  Column3=c("order1,order2,order3", "order4,order5", "order6,order7"))

方案1:tidyverse生态实现(兼容性好)

通过先将待拆分列转为同长度列表列,再同时展开的方式保证元素按位置对应,不会生成笛卡尔积:

library(dplyr)
library(tidyr)
library(stringr)

df %>%
  rowwise() %>%
  mutate(
    Column2 = list(str_split(Column2, "-")[[1]]),
    Column3 = list(str_split(Column3, ",")[[1]])
  ) %>%
  unnest(c(Column2, Column3))

如果使用tidyr 1.2.0及以上版本,可直接用separate_longer_delim简化写法:

library(tidyr)

df %>%
  separate_longer_delim(Column2, delim = "-") %>%
  separate_longer_delim(Column3, delim = ",")

方案2:基础R实现

无需加载第三方包的原生实现:

result <- do.call(rbind, lapply(seq(nrow(df)), function(i) {
  col2 <- strsplit(df$Column2[i], "-")[[1]]
  col3 <- strsplit(df$Column3[i], ",")[[1]]
  data.frame(Column1 = rep(df$Column1[i], length(col2)), Column2 = col2, Column3 = col3)
}))

输出结果

两种方案最终输出一致,符合需求:

Column1 Column2 Column3
1       1  craft1  order1
2       1  craft2  order2
3       1  craft3  order3
4       2  craft4  order4
5       2  craft5  order5
6       3  craft6  order6
7       3  craft7  order7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:24:03