简体   繁体   English

如何将数值向量转换为二进制数?

[英]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"  

Option 1: Use == (assumes that you only have these two options). 选项1:使用== (假设您只有这两个选项)。

as.numeric(x == "Male")
#  [1] 1 1 0 0 1 0 0 0 0 1

Option 2: Use a named key. 选项2:使用命名密钥。

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 

Option 3: Use factor specifying the labels. 选项3:使用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.

相关问题 如何使用 tidyverse 将数字(char)转换为数字(数字) - How do I convert numbers (in char) to numbers (in numeric) using tidyverse 如何将数值数据集转换为 R 中的二进制值? - How do I convert a dataset of numeric values into binary values in R? 如何正确地将写为字符的数字向量转换为数字类型? - How properly convert vector of numbers written as character into numeric type? 如何将字符串中的所有实数(甚至是负数和科学数)提取到数字向量中? - How do I extract all real numbers (even negative and scientific) from a string into a numeric vector? 根据限制将数字向量转换为二进制 (0/1) - Convert numeric vector to binary (0/1) based on limit 如何在 R 中编写数字向量 - How do I write the numeric vector in R 为什么as.numeric将矩阵转换为向量,如何将结果保留为矩阵? - Why does as.numeric convert a matrix to a vector, and how do I keep the result as a matrix? 如何根据列是否全部为数字(但采用字符格式)将整列转换为数字? - How do I convert an entire column to numeric based on whether the column is all numbers (but in character format)? 如何将字符向量转换为数字? - How to convert a character vector to numeric? 如何将具有离散值范围的数值向量转换为因子? - How can I convert a numeric vector with discreete value ranges into a factor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM