2017-10-11 55 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

好點我應該抓住那個。 –