我有以下数据框:计数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))
谢谢!
或'mutate(Count = n_distinct(Month [Volume> 0]))' –
谢谢@AndrewGustar!如果您将此作为答案编写,我会高兴地接受,因为它只需对我的当前代码进行最小限度的更改。 – Anna