B. Davis
B. Davis

Reputation: 3441

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?

Thanks!

Upvotes: 3

Views: 6582

Answers (2)

MichaelChirico
MichaelChirico

Reputation: 34703

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.

Upvotes: 3

CPhil
CPhil

Reputation: 927

dplyr has a count function which does exactly this.

dat %>% count(Number,Bin)

Upvotes: 5

Related Questions