Begin forwarded message:

From: Peter Dalgaard <pda...@gmail.com>
Date: August 15, 2010 3:43:31 PM EDT
To: phgrosj...@sciviews.org
Cc: r-help@r-project.org
Subject: Re: [R] as.logical(factor) behaviour

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


What about changing it to behave thusly:

> as.logical.factor <- function(vec) as.logical(as.numeric(factor(vec))-1 )

> as.logical(as.numeric(factor(c("TRUE", "FALSE", NA)))-1 )
[1]  TRUE FALSE    NA
> as.logical(as.numeric(factor(c(TRUE, FALSE, NA)))-1 )
[1]  TRUE FALSE    NA



--

David Winsemius, MD
West Hartford, CT

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to