将逻辑(布尔)向量强制为0和1 [英] Coerce logical (boolean) vector to 0 and 1
问题描述
我有一个数字矢量:
a <- 1:4
# [1] 1 2 3 4
检查'a'中的值是否大于2:
Check if values in 'a' is larger than 2:
a > 2
# [1] FALSE FALSE TRUE TRUE
但是,我希望我的结果表示为0
和1
,而不是FALSE
和TRUE
.目前,我正在使用以下方法.
However, instead of FALSE
and TRUE
, I want my result to be expressed as 0
and 1
. Currently I am using the following method.
b <- (a > 2)
b[b == TRUE] <- 1
b[b == FALSE] <- 0
有没有更简单的方法?
推荐答案
有几种方法可以解决此问题.
There are a few ways you can go about this.
-
使用
ifelse
b <- ifelse(a > 2, 1, 0)
这只是精确编写问题内容的一种简单方法:如果条件返回TRUE
,则将值设置为1,否则将其设置为0.
This is just a simpler way of writing exactly what you've written in the question: if the condition returns TRUE
, set the value to 1, otherwise set it to 0.
使用as.numeric
b <- as.numeric(a > 2)
使用此功能可以轻松地将逻辑值转换为其数值等效项.如人们所料,TRUE
设置为1,FALSE
设置为0.
Logical values can be converted to their numeric equivalents easily using this function. As one might expect, TRUE
is set to 1 and FALSE
to 0.
as.numeric
的懒版本
b <- 1*(a > 2)
当R看到逻辑值与数字值相乘时,它会自动将逻辑强制为它们的数字等效值.因此,可以通过乘以1来懒惰地转换逻辑值(从程序员的角度来看).
When R sees the multiplication of logical values by a numeric value, it automatically coerces the logicals to their numeric equivalents. Thus logical values can be converted lazily (from a programmer's standpoint) by multiplying by 1.
这篇关于将逻辑(布尔)向量强制为0和1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!