2017-06-21 45 views
0

我目前有多个表需要合并。例如,我有tbl_1,tbl_2和tbl_3。我想以结果表的形式达到最终结果。R合并具有一个标识符的表和其他具有相同名称的列会加起来

tbl_1: 
ID trx_1 Cre_counts Deb_counts 
1 10  9  8 
2 5   6  5 
3 10  4  3 

tbl_2: 
ID trx_2 Unk_counts Deb_counts 
1 10  1  2 
2 5  6  5 
3 10  3  7 

tbl_3: 
ID trx_3 Unk_counts Ckc_counts 
1 3  4  4 
2 2  4  3 
3 8  7  6 

result: 
ID trx_1 tx_2 trx_3 Cre_counts Deb_counts Unk_counts Ckc_counts 
1 10  10  3   9  10  5   4 
2 5  5  2   6  10  10   3 
3 10  10  8   4  10  10   6 

我有尝试通过“ID”合并三个表,但列名会变为Deb_counts.x,Deb_counts.y ......我可以使用变换(),rowSums()采取一些额外的步骤使其工作。但我想知道有没有更简单的方法来做到这一点?谢谢!

+0

,要合并一些值并添加其他值,则需要进行至少2 ST eps – Cath

+0

是的,我明白这一点。目前,我正在采取的步骤不止两个步骤。我首先合并所有表格,然后使用rowSums()添加我想要添加的所有列。然后,删除旧的列。只是想知道你是否知道更简单的方法来做到这一点?也许只有2个步骤。 – VeraShao

+0

嗨,希望这个链接帮助,几乎相同的问题。 https://stackoverflow.com/questions/16018863/combine-data-frames-summing-up-values-of-identical-columns-in-r – Wen

回答

2

也许不是最优雅的,但这里有一个办法:

首先,你需要把你的表到一个列表:

l_tbl <- mget(ls(pattern="^tbl")) 

然后你通过列表​​,在2台工作一时间,这要归功于Reduce,首先将普通列,那么合并:

Reduce(function(x, y) { 
      col_com <- setdiff(intersect(names(x), names(y)), "ID") 
      if(length(col_com)) { 
       x[, col_com] <- x[, col_com] + y[, col_com] 
       y <- y[, !(names(y) %in% col_com)] # you only keep the "not common" columns in the second table 
      } 
       return(merge(x, y, by="ID")) 
     }, l_tbl) 

    ID trx_1 Cre_counts trx_3 Ckc_counts trx_2 Deb_counts Unk_counts 
1 1 10   9  3   4 10   10   5 
2 2  5   6  2   3  5   10   10 
3 3 10   4  8   6 10   10   10 
你不只是要合并
+0

我在x [,col_com] + y [,col_com]:二元运算符的非数字参数。不确定原因。第一步是好的。我忘了提及。不是每两个表都有相同的列名,所以有时候,col_com将是字符(0)。这是问题的原因吗? – VeraShao

+0

@VeraShao这不会是一个问题,因为我检查col_com是否至少有一个长度。我不知道为什么你会得到一个错误,除非你的公共cols不是全部数字 – Cath

相关问题