How do I change all the 0,1 values to No, Yes in my whole dataset, not just for one variable? Thanks
CodePudding user response:
With tidyverse
, we can apply a function across all columns using case_when
(providing multiple ifelse
statements).
library(tidyverse)
df %>%
mutate(across(everything(), ~ case_when(. == 0 ~ "No",
. == 1 ~ "Yes",
TRUE ~ NA_character_)))
Or in base R, we can just replace all instances of 0 with No
, and then the same for 1
.
df[df == 0] <- "No"
df[df == 1] <- "Yes"
Output
x y z
1 No Yes Yes
2 Yes No No
3 Yes No No
4 Yes Yes No
Data
df <- data.frame(x = c(0, 1, 1, 1), y = c(1, 0, 0, 1), z = c(1, 0, 0, 0))
# x y z
#1 0 1 1
#2 1 0 0
#3 1 0 0
#4 1 1 0
CodePudding user response:
Though I prefer the base R method, this alternate tidyverse
solution using recode()
seems easier to read and understand than base R when you return to it later:
df <- data.frame(x = c(0, 1, 1, 1), y = c(1, 0, 0, 1), z = c(1, 0, 0, 0))
df %>%
mutate(across(
everything(),
~ recode(., "0" = "No", "1" = "Yes")
))
Output:
x y z
1 No Yes Yes
2 Yes No No
3 Yes No No
4 Yes Yes No