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

如何在R Data Frame中拆分列表型Product列并展开为多行?

拆分R数据框中多值Product列并保留对应ID

输入数据

先还原你提供的输入数据框:

df <- data.frame(
  ID = c(1, 2, 3),
  Product = c("'desk','chair','clock'", NA, "'pen'"),
  stringsAsFactors = FALSE
)

解决方案

方法1:使用tidyverse工具链(推荐)

利用tidyr::separate_rows()快速实现多值列拆分,自动匹配对应ID,同时处理NA行:

library(tidyverse)

# 拆分多行、清理空格并移除NA行
result <- df %>%
  separate_rows(Product, sep = ",") %>%
  mutate(Product = str_trim(Product)) %>%
  drop_na(Product)

print(result)

方法2:Base R实现(无需额外包)

通过基础R函数完成拆分逻辑:

# 筛选非NA行
non_na_rows <- df[!is.na(df$Product), ]
# 按逗号拆分Product列
split_products <- strsplit(non_na_rows$Product, ",")
# 生成对应ID和拆分后的Product数据框
result_base <- data.frame(
  ID = rep(non_na_rows$ID, sapply(split_products, length)),
  Product = unlist(split_products),
  stringsAsFactors = FALSE
)
# 清理每个Product值的前后空格
result_base$Product <- trimws(result_base$Product)

print(result_base)

输出结果

两种方法都会得到如下格式的结果:

IDProduct
1'desk'
1'chair'
1'clock'
3'pen'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:06:03