Home > other >  OR-condition for Lambda function when Filtering Multiple Columns Dplyr
OR-condition for Lambda function when Filtering Multiple Columns Dplyr

Time:11-18

Please take a moment to consider the following dataset:

my_df <- data.frame(socks = c(1,1,0,1,0,0),
                    hat = c(0,1,1,0,0,0),
                    species = c('frog','pigeon','pigeon','cow','monkey','cow'),
                    gender = c('M','F','M','F','M','M'))

acc <- c('socks','hat')

I am attempting to filter this dataset to include all observations where EITHER the socks OR hat animal accessory variables are equal to 1 (Rows 1-4). I also need to use a vector to hold the names of the columns for the animal accessory variables so I can run this command within a larger function.

Thus far, I have tried the following:

accessorized <- my_df %>% filter_at(vars(acc),all_vars(.==1))
accessorized <- my_df %>% filter(across(acc,~.x==1))

and both return a dataframe containing only those observations where BOTH hat & socks = 1 (Row 2)

Does anybody have suggestions for how to modify this lambda-function to check for equality to 1 across hat & socks via OR rather than AND?

Any help would be greatly appreciated!

CodePudding user response:

Well, I made a silly mistake with my scoped filter_at command, which works when written as the following:

accessorized <- my_df %>% filter_at(vars(acc),any_vars(.==1))

However, it would still be great to know how to modify the lambda function!

CodePudding user response:

When i try the across method I get this message:

Using across() in filter() is deprecated, use if_any() or if_all().

And if_any seems to have the expected output:

my_df %>% filter(if_any(acc,~.x==1))

#  socks hat species gender
#1     1   0    frog      M
#2     1   1  pigeon      F
#3     0   1  pigeon      M
#4     1   0     cow      F
  • Related