2017-10-11 72 views
0

我有以下数据框:计数n_distinct符合条件

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

谢谢!

+2

或'mutate(Count = n_distinct(Month [Volume> 0]))' –

+1

谢谢@AndrewGustar!如果您将此作为答案编写,我会高兴地接受,因为它只需对我的当前代码进行最小限度的更改。 – Anna

回答

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 
1

而不是使用n_distinct功能,我们可以使用duplicated功能以及包括Volume > 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 
0

尝试:

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

长度给出了条目的总数,而不是唯一条目的数量。但是,如果我使用n_distinct而不是长度,我会得到我想要的输出! – Anna

+1

好点我应该抓住那个。 –