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 change an entire column in conditional on another column's value?

I have a column chrBoolean with values ‘true’ ‘false’ and I want to have a new column booleanNew which takes on boolean values TURE/FALSE given the value of chrBoolean. So basically something like:

chrBoolean = c('true', 'true', 'false', 'false', 'true', NA)

booleanNew <- FALSE
booleanNew[chrBoolean == 'true'] <- TRUE
booleanNew[is.na(chrBoolean)] <- NA

desired values for booleanNew:
booleanNew = c(TRUE, TRUE, FALSE, FALSE, TRUE, NA)

I tried using mutate with a case_when but I am not very familiar with r and it didn’t work yet for me. And all example I find is always something like chrBoolean[chrBoolean == 'true'] <- TRUE but never changing one column conditional on another.

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

>Solution :

chrBoolean = c('true', 'true', 'false', 'false', 'true', NA)

booleanNew <- as.logical(chrBoolean)

[1]  TRUE  TRUE FALSE FALSE  TRUE    NA

if you wanted to do this using dplyr::mutate it would be

df %>%
 mutate(booleanNew = as.logical(chrBoolean))
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