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
Change the Position of the Strip Label in Ggplot from the Top to the Bottom
Why Has Data.Table Defined := Rather Than Overloading <-
Error: Vector Memory Exhausted (Limit Reached) R 3.5.0 MACos
Knitr Wont Compile PDF: "Error in Tools::File_Path_As_Absolute(Output_File)"
How to Group by Two Columns in R
Add Image in Title Page of Rmarkdown PDF
Add Values to a Reactive Table in Shiny
Creating (And Accessing) a Sparse Matrix with Na Default Entries
Export Data Frames to Excel via Xlsx with Conditional Formatting
R Command Line Passing a Filename to Script in Arguments (Windows)
Non-Numeric Argument to Binary Operator Error in R
What Does the @ Symbol Mean in R
Annotate Ggplot with an Extra Tick and Label
Row Sums Over Columns with a Certain Pattern in Their Name
How to Scrape/Automatically Download PDF Files from a Document Search Web Interface in R