[R] as.logical(factor) behaviour
Philippe Grosjean
phgrosjean at sciviews.org
Sun Aug 15 17:51:24 CEST 2010
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,
Philippe
On 15/08/10 16:09, R Help wrote:
> The problem is that, underneath the factors are actually numbers (1
> and 2), where as, if you extract the levels and then get the logical,
> it converts them to strings and then to logicals. I run into this
> problem ALL THE TIME with numerics in a dataset. Consider the
> following:
>
>> factor(c(3,6,5,2,7,8,4))
> [1] 3 6 5 2 7 8 4
> Levels: 2 3 4 5 6 7 8
>> as.numeric(factor(c(3,6,5,2,7,8,4)))
> [1] 2 5 4 1 6 7 3
>> as.numeric(as.character(factor(c(3,6,5,2,7,8,4))))
> [1] 2 3 4 5 6 7 8
>
> as.logical converts all non-zeros to TRUE, and 0 to false:
>> as.logical(0:10)
> [1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
>
> Hope that helps,
> Sam
>
> On Sun, Aug 15, 2010 at 5:32 AM, Philippe Grosjean
> <phgrosjean at sciviews.org> wrote:
>> Hello,
>>
>> According to ?as.logical:
>>
>> "as.logical attempts to coerce its argument to be of logical type. For
>> factors, this uses the levels (labels)."
>>
>> However,
>>
>>> as.logical(factor(c("FALSE", "TRUE")))
>> [1] TRUE TRUE
>>
>> Shouldn't it be the same as:
>>
>>> as.logical(levels(factor(c("FALSE", "TRUE"))))
>> [1] FALSE TRUE
>>
>> according to the documentation? Did I miss something here?
>>
>>> sessionInfo()
>> R version 2.11.1 RC (2010-05-29 r52140)
>> x86_64-apple-darwin9.8.0
>>
>> locale:
>> [1] C/UTF-8/C/C/C/C
>>
>> attached base packages:
>> [1] stats graphics grDevices utils datasets methods base
>>
>> Thanks,
>>
>> Philippe
>> --
>> ..............................................<°}))><........
>> ) ) ) ) )
>> ( ( ( ( ( Prof. Philippe Grosjean
>> ) ) ) ) )
>> ( ( ( ( ( Numerical Ecology of Aquatic Systems
>> ) ) ) ) ) Mons University, Belgium
>> ( ( ( ( (
>> ..............................................................
>>
>> ______________________________________________
>> R-help at 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.
>>
>
>
More information about the R-help
mailing list