【发布时间】: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>0])) -
谢谢@AndrewGustar!如果您将其写为答案,我将很乐意接受,因为它需要对我当前的代码进行最少的更改