I am new to R coding and I am trying to work on a project to automate some of my reports.
May I know how to filter with several similar conditions? For instance, a machine has 3 types of error: Part A is inoperative, Part B is inoperative, Part C is inoperative.
I am hoping to filter out all of the instances that the machine is inoperative, but I do not want to write a lengthy code like:
x <- y %>% filter(condition == "Part A is inoperative"| condition == "Part B is inoperative" |condition == "Part C is inoperative")
Is there a simpler way to code? something like x <- y %>% filter(condition == "Part A,B,C is inoperative")
Any suggestion is appreciated.
Thank you
CodePudding user response:
You can create a vector to filter
dynamically.
library(dplyr)
filter_values <- c('A', 'B', 'C')
x <- y %>% filter(condition %in% sprintf('Part %s is inoperative',filter_values))
where
sprintf('Part %s is inoperative', filter_values) #returns
#[1] "Part A is inoperative" "Part B is inoperative" "Part C is inoperative"
CodePudding user response:
You can use the amazing grepl
within your filter:
x <- y %>% filter(grepl("Part [ABC] is inoperative", condition))
If you want to extend you condition to Parts "D" and "E", use an hyphen:
x <- y %>% filter(grepl("Part [A-E] is inoperative", condition))
Fun fact: if you prefer grep
, you can combine it with slice
instead of filter
:
x <- y %>% slice(grep("Part [ABC] is inoperative", condition))
CodePudding user response:
We could use base R
filter_values <- c('A', 'B', 'C')
x <- subset(y, condition %in% paste('Part', filter_values, 'is inoperative'))