Counting unique variables within a unique variables [R]

偶尔善良 提交于 2019-12-25 06:37:00

问题


Suppose this is my data:

X   Y   Z
1   1   2323   
1   1   45
1   1   67 
1   2   1
1   2   90
1   3   34
1   3   1267
1   3   623
1   4   81
1   4   501
2   1   456
2   1   78
2   2   41
2   2   56
2   3   90
2   3   71
2   4   24
2   4   98
2   5   42
2   5   361

How do I count the values of Z for each unique variable Y for each separate X so that I can get a dataframe that looks like:

X   Y   Z
1   1   2435
1   2   91
1   3   1924
1   4   582
2   1   534
2   2   97
2   3   161
2   4   122
2   5   403

回答1:


Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate:

 > aggregate( Z ~ X + Y, data=dat, FUN=sum)

  X Y    Z
1 1 1 2435
2 2 1  534
3 1 2   91
4 2 2   97
5 1 3 1924
6 2 3  161
7 1 4  582
8 2 4  122
9 2 5  403

Could also have used xtabs which returns a table object and then turn it into a dataframe with as.data.frame:

 as.data.frame( xtabs( Z ~ X+Y, data=dat) )


来源:https://stackoverflow.com/questions/22963799/counting-unique-variables-within-a-unique-variables-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!