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 a dataframe by column, depending on the value of another column

I would like to filter something similar to the following dataframe:

A    B    C    D    E
1    0    0.2  2    5
1    0    0.5  5    0
1    7    0.3  4    4
0    2    20   2    2
1    0    0.9  2    1
0    7    17   4    2

How can I remove those rows with values <0.3 for column C if A==1 and those rows with values <20 for column C if A==0?

This would be my expected output:

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

A    B    C    D    E
1    0    0.5  5    0
1    7    0.3  4    4
0    2    20   2    2
1    0    0.9  2    1

I’ve tryed:

library(dplyr)
test<-df %>% {if (A == '1') filter(.,C < 0.3) else filter(.,C < 20)}

But I am not achieving the expected results.

Thanks!

>Solution :

You were close,

& stands for and
| stands for or

library(dplyr)

test <- df %>% filter(!(A==1 & C < 0.3 | A==0 & C < 20))
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