[R] ddply to count frequency of combinations

David Winsemius dwinsemius at comcast.net
Tue Jun 21 22:19:46 CEST 2011


On Jun 21, 2011, at 2:30 PM, Idris Raja wrote:

> I have a dataframe df with two columns x and y. I want to count the  
> number
> of times a unique x, y combination occurs.
>
> For example
>
> x<- c(1,2,3,4,5,1,2,3,4)
> y<- c(1,2,3,4,5,1,2,4,1)
>
> df<-as.data.frame(cbind(x, y))
>
> #what is the correct way to use ddply for this example?
> ddply(df, c('x','y', summarize, ??)
>
> #desired output -- format and order doesn't matter
> # (x, y) count
> #--------------------
> # (1, 1) 2
> # (2, 2) 2
> # (3, 3) 1
> # (4, 4) 1
> # (5, 5) 1
> # (2, 3) 1
> # (3, 4) 1
> # (4, 1) 1
>

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

Did you know that there is a newsgroup specifically set up for plyr  
questions?

manipulatr at googlegroups.com

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list