在 R 中,什么评估为真/假? [英] What evaluates to True/False in R?
问题描述
例如,在 Ruby 中,只有 nil 和 false 是 false.R 中的内容是什么?
For example, in Ruby, only nil and false are false. What is what in R?
例如:5==TRUE
和 5==FALSE
都评估为 FALSE.但是,1==TRUE
是 TRUE
.是否有任何关于(对象、数字等)评估结果的一般规则?
e.g.: 5==TRUE
and 5==FALSE
both evaluate to FALSE. However, 1==TRUE
is TRUE
. Is there any general rule as to what (objects, numbers, etc.) evaluate to?
推荐答案
这在 ?logical
中有记录.其中的相关部分是:
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
那里的第二段解释了您所看到的行为,即 5 == 1L
和 5 == 0L
分别应该返回 FALSE
,其中 1 == 1L
和 0 == 0L
对于 1 == TRUE
和 0 == 应该为 TRUEFALSE
分别.我相信这些不是在测试您希望他们测试的东西;比较是基于 R 中 TRUE
和 FALSE
的数值表示,即强制转换为数值时它们采用的数值.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
但是,只有 TRUE
保证为 TRUE
:
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
是 identical(x, TRUE)
的包装,从 ?isTRUE
我们注意到:
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
同样,只有 FALSE
保证完全等于 FALSE
.
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
如果这与您有关,请始终使用 isTRUE()
或 identical(x, FALSE)
来检查与 TRUE
和 的等价性>FALSE
分别.==
没有按照你的想法做.
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
这篇关于在 R 中,什么评估为真/假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!