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

R中如何将data.frame重复键对应的字段合并为逗号分隔值

R实现按指定字段分组拼接同组文本值

你可以通过以下三种常用方案实现需求:

  • 基础R方案(无需安装额外依赖包)
    使用aggregate函数按fignum分组,拼接同组的codefile值:
    cf_wanted <- aggregate(codefile ~ fignum, data = cf, paste, collapse = ", ")
    
  • tidyverse/dplyr方案
    用分组汇总逻辑实现,适合已经在使用tidyverse生态的场景:
    library(dplyr)
    cf_wanted <- cf %>%
      group_by(fignum) %>%
      summarise(codefile = paste(codefile, collapse = ", ")) %>%
      ungroup()
    # 如果需要严格保持原数据中fignum的出现顺序,可以新增排序逻辑:
    # cf_wanted <- cf %>%
    #   mutate(fignum = forcats::fct_inorder(fignum)) %>%
    #   group_by(fignum) %>%
    #   summarise(codefile = paste(codefile, collapse = ", ")) %>%
    #   ungroup() %>%
    #   mutate(fignum = as.character(fignum))
    
  • data.table方案(适合处理大体积数据,运行效率更高)
    library(data.table)
    setDT(cf)
    cf_wanted <- cf[, .(codefile = paste(codefile, collapse = ", ")), by = fignum]
    

以上三种方案输出的结果都和你预期的示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:02