[英]How do I convert a numeric vector into binary numbers?
I converted a factor into a numeric vector ie from "Male" and "Female" to "1" and "2" with the R code, "as.numeric(data$Gender)". 我用R代码“ as.numeric(data $ Gender)”将一个因子转换为数值向量,即从“男性”和“女性”到“ 1”和“ 2”。 However, I would like to convert the numeric vector into binary numbers ie from "1" representing "Male" and "2" representing "Female", to "1" representing "Male" and "0" representing "Female".
但是,我想将数值向量转换为二进制数,即从代表“ Male”的“ 1”和代表“ Female”的“ 2”到代表“ Male”的“ 1”和代表“ Female”的“ 0”。 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
指定标签。 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())
:
as.numeric(as.character(factor(x, c("Male", "Female"), labels = c(1, 0))))
# [1] 1 1 0 0 1 0 0 0 0 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.