Add count of unique / distinct values by group to the original data

Here’s a solution with the dplyr package – it has n_distinct() as a wrapper for length(unique()).

df %>%
  group_by(color) %>%
  mutate(unique_types = n_distinct(type))

Leave a Comment