0
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?

showkey
  • 482
  • 42
  • 140
  • 295
  • May I ask why? Is `tapply` not working for you as expected in some way? The general solution would be (if you want to use `aggregate`) would be to first `aggregate` and then `reshape`. Something like: `reshape(aggregate(sale ~ year + province, dat, sum), direction = "wide", idvar="year", timevar="province")`, but not sure why, so hesitant to post this as an answer. – A5C1D2H2I1M1N2O1R2T1 Nov 04 '13 at 05:31
  • Another option would be using `xtabs`, the result is in the format you want: `xtabs(sale~year+province, data=dat)` – Jilber Urbina Nov 04 '13 at 10:00

1 Answers1

0

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.

IRTFM
  • 258,963
  • 21
  • 364
  • 487