【问题标题】:Count n_distinct with a condition使用条件计数 n_distinct
【发布时间】:2017-10-11 16:41:57
【问题描述】:

我有以下数据框:

df<-data.frame(Name= c(rep("A",3), rep("B",5)), Month = c(1,2,3,1,2,3,3,3), Volume = c(50,0,50,50,50,50,50,50))

我想更新一个“计数”列来表示每个名称的唯一月份数:

df<-df%>%
  group_by(Name) %>%
  mutate(Count = n_distinct(Month))

但是,我如何添加一个过滤器,以便我只计算对应值 > 0 的月份?这是我想要的输出:

df<-data.frame(Name= c(rep("A",3), rep("B",5)), Month = c(1,2,3,1,2,3,3,3), Volume = c(50,0,50,50,50,50,50,50), Count = c(2,2,2,3,3,3,3,3))

谢谢!

【问题讨论】:

  • mutate(Count = n_distinct(Month[Volume&gt;0]))
  • 谢谢@AndrewGustar!如果您将其写为答案,我将很乐意接受,因为它需要对我当前的代码进行最少的更改

标签: r dplyr


【解决方案1】:

你只需要给Month添加一个条件...

df <- df %>%
      group_by(Name) %>%
      mutate(Count = n_distinct(Month[Volume>0]))

df
# A tibble: 8 x 4
# Groups:   Name [2]
    Name Month Volume Count
  <fctr> <dbl>  <dbl> <int>
1      A     1     50     2
2      A     2      0     2
3      A     3     50     2
4      B     1     50     3
5      B     2     50     3
6      B     3     50     3
7      B     3     50     3
8      B     3     50     3

【讨论】:

    【解决方案2】:

    除了使用n_distinct函数,我们可以使用duplicated函数以及在逻辑表达式中包含Volume &gt; 0

    df %>%
        group_by(Name) %>%
        mutate(Count = sum(!duplicated(Month) & Volume > 0)) # not duplicated, Volume > 0
    
        Name Month Volume Count
      <fctr> <dbl>  <dbl> <int>
    1      A     1     50     2
    2      A     2      0     2
    3      A     3     50     2
    4      B     1     50     3
    5      B     2     50     3
    6      B     3     50     3
    7      B     3     50     3
    8      B     3     50     3
    

    【讨论】:

      【解决方案3】:

      试试:

      df%>%
        group_by(Name) %>%
        mutate(Count = n_unique(Month[Volume >0]))
      

      【讨论】:

      • length 给了我条目的总数,而不是唯一条目的数量。但是,如果我使用 n_distinct 而不是长度,我会得到我想要的输出!
      猜你喜欢
      • 2016-04-10
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多