[R] How to do more advanced cross tabulation in R?

Domenico Vistocco vistocco at unicas.it
Wed Jan 23 09:06:23 CET 2008


You could have a look at the reshape package.

Ciao,
domenico

tom soyer wrote:
> Hi,
>
> I am trying to reproduce some functionalities of Excel pivot table in R,
> sadly, I couldn't figure out how to do it. I am wondering if this is even
> possible in R. Does anyone know?
>
> Here is an example:
>
> year=rep(2003,16)
> quarter=rep(1:4,each=4)
> sales=1:16
> company=rep(c("a","b","c","d"),4)
> df=data.frame(year,quarter,sales,company) #this is the database
>
> I would like to construct a cross tabulation table like this:
>   2003           #a row of year(s)
>    1   2   3   4 #a row of quarters of each year
> a 1   2   3   4
> b 5   6   7   8
> c 9  10  11 12
> c 13 14 15 16
>                      #maybe add a row of subtotal for each quarter at the
> end.
>
> I tried xtabs, but all I could produce is this, unfortunately:
>  xtabs(sales~year+quarter, data=df)
>       quarter
> year    1  2  3  4
>   2003 10 26 42 58
>
> or this:
>
>
>  xtabs(sales~year+quarter+company, data=df)
> , , company = a
>
>       quarter
> year    1  2  3  4
>   2003  1  5  9 13
>
> , , company = b
>
>       quarter
> year    1  2  3  4
>   2003  2  6 10 14
>
> , , company = c
>
>       quarter
> year    1  2  3  4
>   2003  3  7 11 15
>
> , , company = d
>
>       quarter
> year    1  2  3  4
>   2003  4  8 12 16
> Thanks!
>
>



More information about the R-help mailing list