I have a column of type chr
that I need as boolean (but leaving the NAs as NAs). The desired conversion is: No = 0, Yes = 1, NA = NA
tmp <- tibble(x = 1:7, y = c("No", "Yes", NA, "Yes", "Yes", "Yes", "No"))
I used the following to mutate; however I don't want a new variable but just change the original y
variable:
tmp = tmp %>% mutate(
z = case_when(
y=="No" ~ 0,
y=="Yes" ~ 1
))
Just another solution which can be useful in case you will need to recode more values in the future
library(dplyr)
tmp$y <- recode(tmp$y, "No" = 0, "Yes" = 1)
or using mutate
in a pipeline
tmp %>%
mutate(y = recode(y, "No" = 0, "Yes" = 1))
Output
# A tibble: 7 x 2
# x y
# <int> <dbl>
# 1 1 0
# 2 2 1
# 3 3 NA
# 4 4 1
# 5 5 1
# 6 6 1
# 7 7 0