我将一个因子转换为数字向量,即从“男性”和“女性”转换为“1”和“2”,其中R代码为“as.numeric(data $ Gender)”。但是,我想将数字矢量转换成二进制数,即从“1”表示“男性”和“2”表示“女性”,“1”表示“男性”,“0”表示“女性”。有人可以请问我如何做到这一点?非常感谢,非常感谢您的帮助。
答案 0 :(得分:4)
以下是三种选择:
示例数据:
set.seed(1)
x <- sample(c("Male", "Female"), 10, TRUE)
x
# [1] "Male" "Male" "Female" "Female" "Male" "Female" "Female" "Female" "Female" "Male"
==
(假设您只有这两个选项)。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
指定标签。factor(x, c("Male", "Female"), labels = c(1, 0))
# [1] 1 1 0 0 1 0 0 0 0 1
# Levels: 1 0
请注意,如果您想要数字向量,您仍然需要as.numeric(as.character())
:
as.numeric(as.character(factor(x, c("Male", "Female"), labels = c(1, 0))))
# [1] 1 1 0 0 1 0 0 0 0 1