问题描述
|
例如,在Ruby中,只有nil和false为false。 R中是什么?
例如:
5==TRUE
和5==FALSE
均为FALSE。但是,1==TRUE
是TRUE
。有什么关于(对象,数字等)结果求值的一般规则?
解决方法
记录在
?logical
上。其相关部分是:
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 == FALSE
应为TRUE。我相信这些并没有测试您想要他们测试的东西;比较是基于R中的TRUE
和FALSE
的数值表示,即当被强制转换为数值时它们取什么数值。
但是,只有TRUE
被保证为TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
是identical(x,TRUE)
的包装,从?isTRUE
起,我们注意到:
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
。
> identical(F,FALSE)
[1] TRUE
> identical(0,FALSE)
[1] FALSE
> F <- \"hello\"
> identical(F,FALSE)
[1] FALSE
如果这与您有关,请始终使用isTRUE()
或identical(x,FALSE)
分别检查TRUE
和FALSE
的等效性。 ==
没有按照你的想法去做。
,T
和TRUE
为True,F
和FALSE
为False。 T
和F
可以重新定义,因此,您只能依赖TRUE
和FALSE
。如果将0与FALSE和1与TRUE进行比较,您会发现它们也相等,因此您可能会认为它们也为True和False。
,如果您考虑一下,将数字与逻辑语句进行比较并没有多大意义。但是,由于0通常与\“ Off \”或\“ False \”关联,而1与\“ On \”或\“ True \”关联,因此R决定允许1 == TRUE
和0 == FALSE
都为真。除非它类似于3 - 2 == TRUE
,否则任何其他数值与布尔的比较都应得出false。