2017-04-03 84 views
3

多個邏輯條件這是我的數據集:如何寫過濾器內

set.seed(327) 

ID <- seq(1:50) 

mou <- sample(c(2000, 2500, 440, 4990, 23000, 450, 3412, 4958, 745, 1000), 
    50, replace=TRUE) 

calls <- sample(c(50, 51, 12, 60, 90, 16, 89, 59, 33, 23, 50, 555), 
    50, replace=TRUE) 

rev <- sample(c(100, 345, 758, 44, 58, 334, 888, 205, 940, 298, 754), 
    50, replace=TRUE) 

dt <- data.frame(mou, calls, rev) 

我的動機是尋找mou其中要求大於34和小於200比100 rev更大,平均小於400. 我開始通過使用dplyr來解決這個問題,但我不太確定如何在濾波器函數內正確使用所需的表達式。

dt %>% filter(???) %>% summarize(mean_mou=mean(mou)) 

請問您能否指導如何正確地在濾波器內構建這個表達式。

回答

1

你可以把你的條件放在filter函數中。你幾乎沒有在你的榜樣:-)

######## 
# Setup 
######## 
set.seed(327) # Setting a seed makes the example reproducible 

ID <- seq(1:50) 
mou <- 
    sample(c(2000, 2500, 440, 4990, 23000, 450, 3412, 4958, 745, 1000), 
     50, 
     replace = TRUE) 
calls <- 
    sample(c(50, 51, 12, 60, 90, 16, 89, 59, 33, 23, 50, 555), 50, replace = TRUE) 
rev <- 
    sample(c(100, 345, 758, 44, 58, 334, 888, 205, 940, 298, 754), 50, replace = TRUE) 

dt <- data.frame(mou, calls, rev) 

library(tidyverse) 

######## 
# Here's the direct answer to your question 
######## 
dt %>% 
    filter(calls > 34 & calls < 200) %>% 
    filter(rev > 100 & rev < 400) %>% # Using two filters makes things more readable 
    summarise(mean_mou = mean(mou)) 

# 3349 
0
dt %>% 
    filter(., calls > 40 & calls < 200 & rev > 100 & rev <400) %>% 
    summarise(mean(mou)) 

    mean(mou) 
1 2403.333 
5

出於完整性:

如果邏輯是你可以簡單地在一個逗號後面添加多個條件:

df %>% 
    filter(calls > 34, calls < 200, rev > 100, rev < 400) 

如果邏輯是您必須使用通常的邏輯or符號:|

df %>% 
    filter(calls > 34 | rev > 100) 

把他們連在一起工作,但一定要注意做了什麼。 例如:

df %>% 
    filter(calls > 34, calls < 200 | rev > 100, rev < 400) 

裝置calls > 34 AND (calls < 200 OR rev > 100) AND rev < 400