I would like to subset a data.frame with a combination of or/and. This is my code using normal R function.
df <- expand.grid(list(A = seq(1, 5), B = seq(1, 5), C = seq(1, 5))) df$value <- seq(1, nrow(df)) df[(df$A == 1 & df$B == 3) | (df$A == 3 & df$B == 2),]
How could I convert them using filter function in dplyr package? Thanks for any suggestions.
In order to Filter or subset rows in R we will be using Dplyr package. Dplyr package in R is provided with filter() function which subsets the rows with multiple conditions on different criteria. We will be using mtcars data to depict the example of filtering or subsetting. Filter or subset the rows in R using dplyr.
All of the dplyr functions take a data frame (or tibble) as the first argument. Rather than forcing the user to either save intermediate objects or nest functions, dplyr provides the %>% operator from magrittr.
subset has a select argument. subset recycles its condition argument. filter supports conditions as separate arguments. filter preserves the class of the column.
dplyr
solution:load library:
library(dplyr)
filter with condition as above:
df %>% filter(A == 1 & B == 3 | A == 3 & B ==2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With