R 中什么评估为 True/False?

2024-04-26

例如,在 Ruby 中,只有 nil 和 false 是 false。 R 中是什么?

e.g.: 5==TRUE and 5==FALSE两者的评估结果均为 FALSE。然而,1==TRUE is 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 and 5 == 0L分别应该返回FALSE, 然而1 == 1L and 0 == 0L应该是 TRUE1 == TRUE and 0 == FALSE分别。我相信这些并不是测试你想要他们测试的东西;而是测试你想要他们测试的东西。比较是基于数字表示的TRUE and FALSE在 R 中,即当强制转换为数字时它们采用什么数值。

然而,仅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() or identical(x, FALSE)检查是否与以下内容等效TRUE and FALSE分别。==没有按照你的想法去做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R 中什么评估为 True/False? 的相关文章

随机推荐