1. 問題
假設(shè)我們有數(shù)據(jù)框df如下:
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
所示ID915和951前面的部分都重復(fù)了,現(xiàn)在我們想把它變成如下
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
我們可以根據(jù)以下命令進行實現(xiàn)
df1 <- aggregate(df[7], df[-7], unique)
# 或者
df2 <- aggregate(df[7], df[-7], FUN = function(X) paste(unique(X), collapse=", "))
2. 解釋
aggregate函數(shù)應(yīng)該是數(shù)據(jù)處理中常用到的函數(shù),它首先將數(shù)據(jù)進行分組(按行),然后對每一組數(shù)據(jù)進行函數(shù)統(tǒng)計。簡單說有點類似sql語言中的group by,可以按照要求把數(shù)據(jù)打組聚合,然后對聚合以后的數(shù)據(jù)進行加和、求平均等各種操作。
applying a function specified by the FUN parameter to each column of sub-data.frames defined by the by input parameter.
aggregate(x ,by,FUN )
# x:待折疊的數(shù)據(jù) by:統(tǒng)計標量 FUN 折疊計算
所以上面的命令意味著將除去ID的數(shù)據(jù)按照行作為統(tǒng)計標量(by)進行ID選擇,將選到的ID作為要進行操作的對象輸入到FUN中。