将逻辑(布尔)向量强制为 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屋!