在R中评估为True/False的是什么?

Rub*_*oob 39 boolean r

例如,在Ruby中,只有nil和false是false.R中的内容是什么?

例如:5==TRUE并且5==FALSE两者都评估为FALSE.但是,1==TRUETRUE.关于(对象,数字等)评估的内容是否有任何一般规则?

Rei*_*son 49

这是记录在案的?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_’.
Run Code Online (Sandbox Code Playgroud)

第二段有解释你所看到的,即行为5 == 1L5 == 0L分别,这都应该回报FALSE,那里的1 == 1L0 == 0L应该为TRUE,1 == TRUE0 == FALSE分别.我相信这些都没有测试你想让他们测试的东西; 比较是基于R 的数值表示TRUEFALSER,即在强制数字时它们采用的数值.

但是,只TRUE保证TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
Run Code Online (Sandbox Code Playgroud)

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).
Run Code Online (Sandbox Code Playgroud)

因此,同样的优点,只FALSE保证完全相等FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
Run Code Online (Sandbox Code Playgroud)

如果这涉及您,一定要使用isTRUE()identical(x, FALSE)与检查等价TRUEFALSE分别.==没有按照你的想法去做.

  • 还有一件事.在"if"条件下,非零数字被视为"TRUE",0被视为"FALSE". (2认同)

Raf*_*ler 5

TTRUE是 True,FFALSE是 False。T但是, andF可以重新定义,因此您应该只依赖TRUEFALSE。如果将 0 与 FALSE 和 1 与 TRUE 进行比较,您会发现它们也相等,因此您可能也认为它们是 True 和 False。

  • 值得注意的是,只有“TRUE”和“FALSE”被保留。`T` 和 `F` 可以重新定义。即 `T &lt;- "hi"` 是有效的,而 `TRUE &lt;- "hi"` 是错误的。 (5认同)
  • @Sacha:这不仅仅是0以外的整数,也不是因为评估(严格来说)。这是因为 `if` 试图将条件强制为逻辑条件(例如 `if("True") print("true!")`)。请参阅 `?"if"` 和 `?as.logic` 了解更多信息。 (2认同)