How to write more than one boolean condition inside a filter

This is my dataset:

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)

      

My motive is to find the average mou

where the number of calls is greater than 34 and less than 200 and rev

greater than 100 and less than 400. I started to approach this problem with dplyr, but not sure how to properly use the desired expression inside the filter function.

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

      

Could you correctly describe this expression inside the filter.

+3


source to share


3 answers


You can put your conditionals in a function filter

. You are almost in your example :-)



########
# 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 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

      

+1


source


For completeness:

If the logic is AND , you can just add a few conditions after the comma:

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

      

If the logic is OR , you must use a regular symbol or

:|



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

      

The chain of their work together, but you need to pay attention to what has been done. For example:

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

      

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

+5


source


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

  mean(mou)
1  2403.333

      

0


source







All Articles