组合在两列R中具有相同值的行 [英] Combine rows which have same value in two columns R

查看:367
本文介绍了组合在两列R中具有相同值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data frame that looks like:

       A      B    C     
1.     80     1    12    
2.     80     1    13    
3.     80     2    14    
4.     81     2    15    
5 .    81     2    16    

我想要:

       A'     B'    C'     
1.     80     1    12 13   
2.     80     2    14    
3.     81     2    15 16    

任何建议包等?

推荐答案

您可以使用 aggregate 通过A和B对C值进行分组,这里使用粘贴 (string concatenation)作为聚合函数:

You can do this using aggregate to group the C values by A and B, here using paste (string concatenation) as the aggregating function:

> df<-data.frame(A=c(80,80,80,81,81),B=c(1,1,2,2,2),C=12:16)
> 
> df
   A B  C
1 80 1 12
2 80 1 13
3 80 2 14
4 81 2 15
5 81 2 16
> 
> aggregate(data=df,C~B+A,FUN=paste)
  B  A      C
1 1 80 12, 13
2 2 80     14
3 2 81 15, 16

这篇关于组合在两列R中具有相同值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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