I converted a factor into a numeric vector i.e. from "Male" and "Female" to "1" and "2" with the R code, "as.numeric(data$Gender)". However, I would like to convert the numeric vector into binary numbers i.e. from "1" representing "Male" and "2" representing "Female", to "1" representing "Male" and "0" representing "Female". Could anybody please kindly advice me on how this could be done? Thank you very much, and your help is very much appreciated.
Here are three alternatives:
Sample data:
set.seed(1)
x <- sample(c("Male", "Female"), 10, TRUE)
x
# [1] "Male" "Male" "Female" "Female" "Male" "Female" "Female" "Female" "Female" "Male"
== (assumes that you only have these two options).as.numeric(x == "Male")
# [1] 1 1 0 0 1 0 0 0 0 1
key <- setNames(0:1, c("Female", "Male"))
key[x]
# Male Male Female Female Male Female Female Female Female Male
# 1 1 0 0 1 0 0 0 0 1
factor specifying the labels.factor(x, c("Male", "Female"), labels = c(1, 0))
# [1] 1 1 0 0 1 0 0 0 0 1
# Levels: 1 0
Note that you'll still need as.numeric(as.character()) if you wanted a numeric vector:
as.numeric(as.character(factor(x, c("Male", "Female"), labels = c(1, 0))))
# [1] 1 1 0 0 1 0 0 0 0 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With