This is something I spent some time searching for. There were several good answers on Stack Overflow detailing how you can get the number of unique values, but I couldn't find any that showed how to count the number of occurrences for each value using dplyr
.
Asked
Active
Viewed 329 times
0

mhovd
- 3,724
- 2
- 21
- 47
-
3`dplyr` does *not* disable *base*: `table(df$val)` – GKi Jun 17 '20 at 10:41
-
`table(df$val)` doesn't provide the number of occurrences of each variable? Can you elaborate? – mhovd Jun 17 '20 at 10:46
-
2Oh yes it does. It gives for 0 3 times, for 1 4 times, for 2 2 times and for 3 1 time. – GKi Jun 17 '20 at 10:54
-
Oh, now I see how to interpret it! Thank you very much, that is much more compact. – mhovd Jun 17 '20 at 11:14
1 Answers
1
df %>% select(val) %>% group_by(val) %>% mutate(count = n()) %>% unique()
This first filters out the value of interest, groups by it, then creates a new column all the unique values, and the number of occurrences of each of those values.
Here is a reproducible example showcasing how it works:
id <- c(1,2,3,4,5,6,7,8,9,0)
val <- c(0,1,2,3,1,1,1,0,0,2)
df <- data.frame(id=id,val=val)
df
#> id val
#> 1 1 0
#> 2 2 1
#> 3 3 2
#> 4 4 3
#> 5 5 1
#> 6 6 1
#> 7 7 1
#> 8 8 0
#> 9 9 0
#> 10 0 2
df %>% select(val) %>% group_by(val) %>% mutate(count = n()) %>% unique()
#> # A tibble: 4 x 2
#> # Groups: val [4]
#> val count
#> <dbl> <int>
#> 1 0 3
#> 2 1 4
#> 3 2 2
#> 4 3 1
Created on 2020-06-17 by the reprex package (v0.3.0)

mhovd
- 3,724
- 2
- 21
- 47