[R] as.logical(factor) behaviour

Peter Dalgaard pdalgd at gmail.com
Sun Aug 15 21:43:31 CEST 2010


Philippe Grosjean wrote:
> Thank you, but I already know that. I am not surprised by this behavior, 
> but by an inconsistency between that behavior and the documentation that 
> says "For factors, this uses the levels (labels).", which it does not.
> Best,

My gut feeling say that the docs need to be changes. The current
situation is a bit silly because de facto, as.logical(f) is always TRUE
(except  for NA handling). However, fixing the code to match the docs
would instead give NA in nearly all cases, and I suspect that has
potential to upset code all over the place.

It is easy enough to try and see what happens:

> as.logical.factor <- function(x)as.logical(levels(x))[x]
> as.logical(factor(0))
[1] NA
> as.logical(factor(FALSE))
[1] FALSE
> as.logical(factor(TRUE))
[1] TRUE
> as.logical(factor(1))
[1] NA
> as.logical("0")
[1] NA


-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list