2017-04-03 43 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