R使用dplyr计数组中不同数量的值的数量

亚马逊人

我想为每个ID值计算不同数量的颜色,并且我希望结果数据框为原始数据框+另一列称为count。在另一个询问相同问题的帖子中,我得到了以下代码,但是该代码似乎对我不起作用

    ID= c('A', 'A', 'A', 'B', 'B', 'B')
    color=c('white', 'green', 'orange', 'white', 'green', 'green')

    d = data.frame (ID, color)
    d %>%
      group_by(ID) %>%
      mutate(count = n_distinct(color))

通过运行此代码,我得到了以下结果:

      ID    color  count
      <fct> <fct>  <int>
      1 A     white      3
      2 A     green      3
      3 A     orange     3
      4 B     white      3
      5 B     green      3
      6 B     green      3

当我想要的是

      ID    color  count
      <fct> <fct>  <int>
      1 A     white      3
      2 A     green      3
      3 A     orange     3
      4 B     white      2
      5 B     green      2
      6 B     green      2

有人可以告诉我我做错了什么,还是使用dplyr进行处理的另一种方法?

安德里

一些注意事项:

# 1. Data set
df = data.frame (
  id = c('A', 'A', 'A', 'B', 'B', 'B'),
  color = c('white', 'green', 'orange', 'white', 'green', 'green'))

# 2. Desired result
df %>%
  group_by(id) %>%
  dplyr::mutate(count = n_distinct(color))

# 3. Result with a number of unique 'color's per 'id'
df %>%
  group_by(id, color) %>%
  dplyr::mutate(count = n()) %>% 
  unique()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章