Changing Binary Variables to Yes/No

R: Converting multiple binary columns into one factor variable whose factors are binary columns

I am guessing that you want to revert a "one-hot encoding" of a variable. Here is a quick way to do it.

apply(df ,1,\(x) names(which(x == "yes"))) |>
purrr::map_chr(~ifelse(length(.x) == 0, NA_character_, .x))

#+ [1] "v1" "v1" "v3" "v1" "v1" "v2" "v1" "v2" "v3" NA

A tidyverse approach would be:

df |>
mutate(ID = row_number()) |>
pivot_longer(cols = c(v1,v2,v3), names_to = "var") |>
filter(value == "yes")

##> ID var value
##> <int> <chr> <chr>
##> 1 1 v1 yes
##> 2 2 v1 yes
##> 3 3 v3 yes
##> 4 4 v1 yes
##> 5 5 v1 yes
##> 6 6 v2 yes
##> 7 7 v1 yes
##> 8 8 v2 yes
##> 9 9 v3 yes

r program changing yes/no variable to 1/0 - variable 'medal' is not a factor

Apart from the obvious typo...

How can I change the yes/no to 0/1?

You need

sport$medal <- factor(sport$medal, levels = c("yes", "no"))

The default behaviour will give you 0 for "no" and 1 for "yes", as "n" comes ahead of "y" in alphabetical order.



Related Topics



Leave a reply



Submit