我有以下數據框:計數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