Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter in R across multiple rows based on multiple conditions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading