Home > Software engineering >  Filter in R across multiple rows based on multiple conditions
Filter in R across multiple rows based on multiple conditions

Time:01-25

In my dataset I have a check all question in which "no" is one the responses. I want to be able determine if any participants clicked "no" (child_tasks_2___0) and then another answer.

Here is some data:

child_tasks_2___0 child_tasks_2___1 child_tasks_2___2 child_tasks_2___3 child_tasks_2___4 
1                  0                 1                 0                    
0                 0                 
2                  1                 1                 0                 0                 0                 
3                  1                 0                 0                 0                 0                 
4                  1                 0                 0                 1                 1                 
5                  1                 0                 0                 0                 0 

            

I tried this code:

results <- survey_all %>% 
  filter(child_tasks_2___0==1 &
         if_any (child_tasks_2___1:child_tasks_2___4)== 1)

However it only filters out child_tasks_2___0==1

CodePudding user response:

The if_any(cols) will return always TRUE if there is any value other than 0 in any of the columns in the row. If we want to compare with a specific value, do the comparison inside each column by making use of a lambda expression (~ .x == 1). In the OP's code, the if_any returns all TRUE and then when it compares with 1, it is doing TRUE == 1 which returns TRUE as 1 is coerced to TRUE

library(dplyr)
survey_all %>% 
   filter(child_tasks_2___0==1 & 
    if_any(child_tasks_2___1:child_tasks_2___4, ~ .x== 1))
  •  Tags:  
  • r
  • Related