[R] ddply to count frequency of combinations

Hadley Wickham hadley at rice.edu
Tue Jun 21 23:49:25 CEST 2011


> Here's a non plyr approach:
>
>> tab.df <- as.data.frame(table(df))
>> tab.df[tab.df$Freq > 0, ]
>   x y Freq
> 1  1 1    2
> 4  4 1    1
> 7  2 2    2
> 13 3 3    1
> 18 3 4    1
> 19 4 4    1
> 25 5 5    1

But look at str(tab.df) - x and y are now factors (or characters).  I
wrote count to avoid this problem.

Also compare:

table(mtcars)
# Error in table(mtcars) : attempt to make a table with >= 2^31 elements

count(mtcars)
#     mpg cyl  disp  hp drat    wt  qsec vs am gear carb freq
# 1  10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4    1
# 2  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4    1
# ...

Hadley


-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-help mailing list