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

How to check whether at least one column is false, ignoring NA in a R dataset?

I have a table like that
| A | B | C |
| ——| ——-| ——-|
| TRUE | NA | FALSE |
| NA | FALSE | NA |
| NA | NA | TRUE |
| NA | NA | NA |

I would like to create a column that takes value TRUE if any column is TRUE (ignoring NA), otherwise, if all columns are FALSE or NA takes value FALSE, and finally takes NA only if all columns are NA.

A B C Global
TRUE NA FALSE TRUE
NA FALSE NA FALSE
NA NA TRUE TRUE
NA NA NA NA

I have tried with the if_any function, but it works only for the TRUE case.

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

df <- data.frame(A = c(T, NA, NA, NA),
                 B = c(NA, F, NA, NA), 
                 C = c(F, NA, T, NA))

df <- df %>%
      mutate (Global = if_any(.cols = c(A,B,C) ,I)

Is there an easy way to achieve that?

>Solution :

as.logical(rowMeans(df,na.rm=T))
[1]  TRUE FALSE  TRUE    NA
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