[R] problem with table()
Dominik Hattrup
dominik.hattrup at googlemail.com
Mon Jan 26 19:47:44 CET 2009
Marc Schwartz schrieb:
> on 01/26/2009 12:23 PM Dominik Hattrup wrote:
>
>> Hey everyone,
>>
>> I am looking for the easiest way to get this table
>>
>> # Table2
>> Year / 2000 / 2002 / 2004
>> Julia / 3 / 4 / 1
>> Peter / 1 / 2 / 4
>> ... / ... / ... / ...
>>
>> out of this one?
>>
>> # Table1
>> name / year / cases
>> Julia / 2000 / 1
>> Julia / 2000 / 2
>> Julia / 2002 / 4
>> Peter / 2000 / 1
>> Julia / 2004 / 1
>> Peter / 2004 / 2
>> Peter / 2002 / 2
>> Peter / 2004 / 2
>> ... / ... / ...
>>
>> Code for table1:
>> name <- c('Julia','Julia','Julia','Peter','Julia','Peter','Peter','Peter')
>> year <- c(2000,2000,2002,2000,2004,2004,2002,2004)
>> cases <- c(1,2,4,1,1,2,2,2)
>> table1 <- data.frame(name,year,cases)
>>
>> Thanks! Dominik
>>
>
> table() generates frequencies from individual values, not from already
> tabulated data.
>
> In this case, you can use xtabs():
>
>
>> xtabs(cases ~ name + year, data = table1)
>>
> year
> name 2000 2002 2004
> Julia 3 4 1
> Peter 1 2 4
>
>
> See ?xtabs
>
> An alternative would be to use tapply():
>
>
>> with(table1, tapply(cases, list(name = name, year = year), sum))
>>
> year
> name 2000 2002 2004
> Julia 3 4 1
> Peter 1 2 4
>
>
> See ?tapply
>
> HTH,
>
> Marc Schwartz
>
>
Thank You for the quick answer. Works perfect! Dominik
More information about the R-help
mailing list