我目前正在研究我的硕士论文,我的部分数据分析在R中。我对它是全新的,所以我一直在学习。
我们正在进行的实验包括个人在一系列回合中玩令牌分配游戏。
我需要更改R中的当前csv文件,以便每个人都出现在一行中,其中inroup,outgroup和self在他们播放的40轮中总结。
目前,数据框如下:
id roundno tokenstoingroup tokenstooutgroup tokenstoself
0001 1 1 0 0
0001 2 0 1 0
0002 1 0 0 1
等...
有许多参与者(超过一千人),并输入每个参与者的每一轮分配。
我的问题是:
如何对此进行总结,以使数据框看起来更像这样?
id totalrounds tokenstoingroup tokenstooutgroup tokenstoself
0001 40 25 13 2
002 40 13 13 14
等...
正如我所说,我对此完全陌生。我试图在网上寻找聚合和总结的东西,但我知道从哪里开始这样复杂的东西。
答案 0 :(得分:2)
您可以将aggregate
功能与cbind
一起使用。例如,让我们创建一个数据框:
test <- data.frame('id'=rep(c('A','B','C'),each=2),'C1'=rep(1,6),'C2'=1:6)
> test
id C1 C2
1 A 1 1
2 A 1 2
3 B 1 3
4 B 1 4
5 C 1 5
6 C 1 6
然后:
test <- aggregate(cbind(C1,C2)~id,data=test,sum)
> test
id C1 C2
1 A 2 3
2 B 2 7
3 C 2 11
答案 1 :(得分:0)
我们可以使用summarise_each
dplyr
library(dplyr)
df1 %>%
group_by(id) %>%
summarise_each(funs(sum), roundno, tokenstoingroup,tokenstooutgroup, tokenstoself)