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

2019-09-27 14:11发布

问题:

This question already has an answer here:

  • Sum by two variables 2 answers

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!

回答1:

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))


标签: r sum