0

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.

mhovd
  • 3,724
  • 2
  • 21
  • 47

1 Answers1

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