-->

What is the rationale for as.logical double coerci

2019-06-15 14:35发布

问题:

I'm trying to understand the coercion rationale for doubles:

as.logical(c(-1, -0.01, 0, 0.01, 0.1,1:10))
#>  [1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#> [12]  TRUE  TRUE  TRUE  TRUE

I can see that coercion happens on a scalar (sign doesn't matter) and that only exactly 0 is coerced to FALSE. I was surprised by this, there seems to be no notion of "closest to..." or rounding to 0L or 1L. I'm curious as to why.

I did try to hunt around for insight here but no success.

I also looked at this related question.

Can someone explain why I should expect each of the above tested values to coerce as they do?

回答1:

My guess would be that this is inherited from C, e.g. from here:

In C true is represented by any numeric value not equal to 0 and false is represented by 0

Also see e.g. here; at the moment I can't find a better source for the official language specification.

A pirated copy of Kernighan and Ritchie 2d ed. I found online (I'd rather not link to it) says on p. 50, Section 3.2, "If-Else" (emphasis added):

The expression is evaluated; if it is true (that is, if expression has a non-zero value), statement 1 is executed. If it is false (expression is zero) and if there is an else part, statement 2 is executed instead.

@hrbrmstr points out that the R internal definition of LOGICAL that's used for the conversion is in Rinternals.h:

#define LOGICAL(x) ((int *) DATAPTR(x))


标签: r boolean r-faq