Reputation: 3441
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
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
Reputation: 927
dplyr has a count function which does exactly this.
dat %>% count(Number,Bin)
Upvotes: 5