How to change yes/no in a column to 1 and 0
If we need to convert multiple values "N", "n", "no", "NO" and all others as "Yes" to 0 and 1, get the first character with substr
, change it to upper case (toupper
, do a comparison (!=
) with "N" and coerce it to binary (as.integer
)
library(dplyr)
clean %>%
mutate(flight = as.integer(toupper(substr(flight, 1, 1)) != "N"))
NOTE: Assume that there are only "Yes", "NO", "no", "N", "n" as values in the column
data
clean <- tibble(flight = c("No", "Yes", "YES", "Y", "no",
"No", "NO", "Y", "n", "y", "No"))
dplyr mutate converting No to 0 and Yes to 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
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
Tensorflow Different Ways to Export and Run Graph in C++
Add Custom CSS Styling to Model Form Django
Python Equivalent of Ruby's .Select
Swift If Or/And Statement Like Python
Check If String Ends with One of the Strings from a List
Don't Wait for a Page to Load Using Selenium in Python
What Does % Do to Strings in Python
In Python, How to Capture the Stdout from a C++ Shared Library to a Variable
Best Way to Set Entry Background Color in Python Gtk3 and Set Back to Default
Closest Equivalent of a Factor Variable in Python Pandas
Function Which Returns the Least-Squares Solution to a Linear Matrix Equation