Question

Let's say I have a data.frame that looks like this:

ID   B
1    1
1    2
1    1
1    3
2    2
2    2
2    2
2    2
3    2
3    10
3    2

Now I want to check the occurrences of B under each ID, such as that for no. 1, 1 happens twice, 2 and 3 happens 1 time each. And in no. 2, only 2 happens 4 times. How should I accomplish this? I tried to use table in ddply but somehow it did not work. Thanks.

Was it helpful?

Solution 2

And here's an aggregate solution:

> with(data, aggregate(B, list(ID=ID, B=B), length))
  ID  B x
1  1  1 2
2  1  2 1
3  2  2 4
4  3  2 2
5  1  3 1
6  3 10 1

OTHER TIPS

It seems like you may just want a table

> table(dat)
##    B
## ID  1 2 3 10
##   1 2 1 1  0
##   2 0 4 0  0
##   3 0 2 0  1

Then the following shows that for ID equal to 1, there are two 1s, one 2, and one 3.

> table(dat)[1, ]
##  1  2  3 10 
##  2  1  1  0 

Here's an approach using "dplyr" (if I understood your question correctly):

library(dplyr)
mydf %.% group_by(ID, B) %.% summarise(count = n())
# Source: local data frame [6 x 3]
# Groups: ID
# 
#   ID  B count
# 1  1  1     2
# 2  1  2     1
# 3  1  3     1
# 4  2  2     4
# 5  3  2     2
# 6  3 10     1

In "plyr", I guess it would be something like:

library(plyr)
ddply(mydf, .(ID, B), summarise, count = length(B))

In base R, you could do something like the following and just remove the rows with 0:

data.frame(table(mydf))
#    ID  B Freq
# 1   1  1    2
# 2   2  1    0
# 3   3  1    0
# 4   1  2    1
# 5   2  2    4
# 6   3  2    2
# 7   1  3    1
# 8   2  3    0
# 9   3  3    0
# 10  1 10    0
# 11  2 10    0
# 12  3 10    1

And the data.table solution because there must be:

data[, .N, by=c('ID','B')]

The above won't work if you try to apply it to a data.frame. It must be converted to a data.table first. With more recent versions of "data.table", this is most easily done with setDT (as recommended by David in the comments):

library(data.table)
setDT(data)[, .N, by=c('ID', 'B')] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top