什么计算为真/假R中? [英] What evaluates to True/False in R?

查看:193
本文介绍了什么计算为真/假R中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在Ruby中,只有零和虚假的都是假的。 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?

推荐答案

这是在案?逻辑。其中的相关部分是:

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 应为TRUE 1 == TRUE 0 == FALSE 分别。我相信这些不是测试你希望他们考什么;比较结果为 TRUE的数值再presentation FALSE 在R,即什么数字的基础上,当强制转换为数字,他们采取的值。

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运算相同的包装(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运算()相同(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆