Home Ask Login Register

Developers Planet

Your answer is one click away!

B. Davis February 2016

count the number of times a number (factor) occurs within each group

With the reproducible data below,

dat <- data.frame(Bin = rep(1:4, each = 50), 
                  Number = sample(5, 200, replace = T, prob = c(1,1,1,2,3))) 

> head(dat)
  Bin Number
1   1      3
2   1      5
3   1      4
4   1      5
5   1      5
6   1      1

I want to count the number of times each Number occurs within each Bin, preferably using dplyr. Said differently, how many occurrences of each level of Number are in each Bin?



CPhil February 2016

dplyr has a count function which does exactly this.

dat %>% count(Number,Bin)

MichaelChirico February 2016

Might as well throw the data.table answer here as well:

setDT(dat)[ , .N, keyby = .(Number, Bin)]

And as user20650 pointed out, base R has a very simple solution:

with(dat, table(Number, Bin))

Just depends on your preferred output format.

Post Status

Asked in February 2016
Viewed 3,087 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life