[R] Fwd: as.logical(factor) behaviour

David Winsemius dwinsemius at comcast.net
Sun Aug 15 21:53:45 CEST 2010



Begin forwarded message:

> From: Peter Dalgaard <pdalgd at gmail.com>
> Date: August 15, 2010 3:43:31 PM EDT
> To: phgrosjean at sciviews.org
> Cc: r-help at 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



More information about the R-help mailing list