Question

dat=data.frame(
    year=c(rep(2007,5),rep(2008,3),rep(2009,3)),
    province=c("a","a","b","c","d","a","c","d","b","c","d"),
    sale=1:11)
tapply(dat$sale,list(dat$year,dat$province),sum)
      a  b  c  d
2007  3  3  4  5
2008  6 NA  7  8
2009 NA  9 10 11

In the case , how can i change the tapply into aggregate to get the same result?

Was it helpful?

Solution

It would not be arranged as a table, but rather as a "long format" presentation.

> aggregate(dat$sale,list(dat$year,dat$province),sum)
   Group.1 Group.2  x
1     2007       a  3
2     2008       a  6
3     2007       b  3
4     2009       b  9
5     2007       c  4
6     2008       c  7
7     2009       c 10
8     2007       d  5
9     2008       d  8
10    2009       d 11

Whether you consider that the same is not clear. The information content is the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top