Home > OS >  How to change an entire column in conditional on another column's value?
How to change an entire column in conditional on another column's value?

Time:09-18

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.

CodePudding user response:

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))

CodePudding user response:

Zimia's answer is better for your particular question. But here is a more general solution based on indexing for cases where direct conversion to logical isn't possible.

> chrBoolean = c('true', 'true', 'false', 'false', 'true', NA)
> vals <- c(true = TRUE, false = FALSE)
> booleanNew <- vals[chrBoolean]
> booleanNew
 true  true false false  true  <NA>
 TRUE  TRUE FALSE FALSE  TRUE    NA

# To drop names
> as.vector(booleanNew)
[1]  TRUE  TRUE FALSE FALSE  TRUE    NA
  •  Tags:  
  • r
  • Related