合并 R 中的重复行并添加包含重复 ID 的新列 [英] Combining duplicated rows in R and adding new column containing IDs of duplicates

查看:19
本文介绍了合并 R 中的重复行并添加包含重复 ID 的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框:

I have a data frame that looks like this:

Chr start   stop    ref alt Hom/het ID  
chr1    5179574 5183384 ref Del Het 719  
chr1    5179574 5184738 ref Del Het 915  
chr1    5179574 5184738 ref Del Het 951  
chr1    5336806 5358384 ref Del Het 376  
chr1    5347979 5358384 ref Del Het 228  

我想合并所有重复的行,合并最后一个 ID 列,以便所有 ID 都在一个行/列中,如下所示:

I would like to merge any duplicate rows, combining the last ID column so that all IDs are in one row/column, like this:

Chr start   stop    ref alt Hom/het ID  
chr1    5179574 5183384 ref Del Het 719  
chr1    5179574 5184738 ref Del Het 915, 951 
chr1    5336806 5358384 ref Del Het 376  
chr1    5347979 5358384 ref Del Het 228  

我发现了人们删除重复项并对一列求和的示例,但我只想将所有 ID 与重复区域组合在一个列表中的单个列中.

I have found examples of people removing duplicates and summing a column, but I just want to combine all IDs with duplicate regions in a list in a single column.

推荐答案

调用 aggregate() 应该可以解决问题.

Some call to aggregate() should do the trick.

这是一个在列表对象中收集 ID 的选项:

Here's an option that collects the ID's in a list object:

(df1 <- aggregate(df[7], df[-7], unique))
#   Chr   start    stop ref alt Hom.het       ID
# 1 chr1 5179574 5183384 ref Del     Het      719
# 2 chr1 5179574 5184738 ref Del     Het 915, 951
# 3 chr1 5336806 5358384 ref Del     Het      376
# 4 chr1 5347979 5358384 ref Del     Het      228

这是一个将它们收集在字符向量中的方法:

And here's one that collects them in a character vector:

df2 <- aggregate(df[7], df[-7], 
                 FUN = function(X) paste(unique(X), collapse=", "))

比较两个选项的结果:

str(df1$ID)
# List of 4
#  $ 0: int 719
#  $ 3: int [1:2] 915 951
#  $ 7: int 376
#  $ 8: int 228

str(df2$ID)
# chr [1:4] "719" "915, 951" "376" "228"

这篇关于合并 R 中的重复行并添加包含重复 ID 的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆