How to sum one variable group by two variables?? R

2019-09-27 13:50发布

This question already has an answer here:

I have one dataframe:

    Date   area    sales

1     201204   shanghai    23

2     201204 beijing     25

3     201204 beijing     16

4     201205 shanghai    55

5     201205 beijing     17

6     201205 shanghai    16

what I want to output is a table as follows:

Date   shanghai  beijing 

201204  23        41

201205  71        17

How would I do this in R? Thanks!

标签: r sum
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-27 14:38

Two options, one with base function aggregate, the other with plyr's ddply. I made up my own data since yours isn't reproducible, but you should be able to get the point:

dat <- data.frame(x1 = sample(letters[1:3], 100, TRUE),
                  x2 = sample(letters[6:3], 100, TRUE),
                  value = rnorm(100))

aggregate(value ~ x1 + x2, data = dat, FUN = 'sum')

library(plyr)
ddply(dat, .(x1,x2), summarize, foo = sum(value))
查看更多
登录 后发表回答