简体   繁体   English

计算唯一变量中的唯一变量[R]

[英]Counting unique variables within a unique variables [R]

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每个唯一变量YZ值,以便获得如下数据框:

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

Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate: 假设数据框被命名为“ dat”,则使用aggregate.formula ,它是aggregate.formula的泛型之一:

 > 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: 还可以使用xtabs返回一个表对象,然后将其转换为带有as.data.frame的数据框:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM