How to add count of unique values by group to R data.frame

后端 未结 3 995
死守一世寂寞
死守一世寂寞 2020-11-22 01:59

I wish to count the number of unique values by grouping of a second variable, and then add the count to the existing data.frame as a new column. For example, if the existing

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:31

    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))
    

提交回复
热议问题