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

如何在R中合并含重复名称的data.frame,将对应列值合并为逗号分隔形式

解决方案

问题分析

你之前的代码存在几个关键问题:

  • group_by("Name") 里的引号是多余的,应直接传入列名 Name
  • 使用 mutate 会保留分组后的所有行,而我们需要将每组聚合为单行,应该用 summarise
  • 未处理重复值(比如reservatol对应的Use列有重复的Pharma),会导致合并后出现冗余内容

代码实现

首先确保安装并加载dplyr包:

# 若未安装则先执行安装
# install.packages("dplyr")
library(dplyr)

然后用以下代码处理数据:

df1 <- data.frame(Name=c("reservatol","reservatol","reservatol","DPG"),
                  Result = c("naturally occurring", "antagonist", "synthetic", "rubber"),
                  Use = c("Pharma", "Pharma", "Drugs and Medication", "Tires"))

# 分组聚合,合并对应列并去重
df_merged <- df1 %>%
  group_by(Name) %>%
  summarise(
    Result = paste(Result, collapse = ", "),  # Result列无重复,直接合并
    Use = paste(unique(Use), collapse = ", ")  # Use列去重后再合并
  ) %>%
  ungroup()  # 取消分组状态

# 查看最终结果
print(df_merged)

输出结果

# A tibble: 2 × 3
  Name        Result                                      Use                         
  <chr>       <chr>                                       <chr>                       
1 DPG         rubber                                      Tires                       
2 reservatol  naturally occurring, antagonist, synthetic  Pharma, Drugs and Medication

基础R替代方案

如果不想依赖dplyr,可以用基础R的aggregate函数实现:

df_merged_base <- aggregate(. ~ Name, data = df1, 
                            FUN = function(x) paste(unique(x), collapse = ", "))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:10:01