[R] combn with factors

Greg Hirson ghirson at ucdavis.edu
Thu Apr 8 07:22:13 CEST 2010


Peter,

Thank you. I'll be sure to include a as.character.

Greg

On 4/7/10 11:40 AM, Peter Ehlers wrote:
>
> On 2010-04-07 11:40, Greg Hirson wrote:
>> Dear list,
>>
>> I have come across this issue:
>>
>> combn(letters[1:5], 3)
>>
>> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
>> [1,] "a" "a" "a" "a" "a" "a" "b" "b" "b" "c"
>> [2,] "b" "b" "b" "c" "c" "d" "c" "c" "d" "d"
>> [3,] "c" "d" "e" "d" "e" "e" "d" "e" "e" "e"
>>
>> combn(factor(letters[1:5]), 3)
>>
>> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
>> [1,] "a" "1" "1" "1" "1" "1" "2" "2" "2" "3"
>> [2,] "b" "2" "2" "3" "3" "4" "3" "3" "4" "4"
>> [3,] "c" "4" "5" "4" "5" "5" "4" "5" "5" "5"
>>
>> I'm not sure why the first combination uses the factor labels and the
>> remaining combinations use the factor value. In the second case, I
>> expected that the labels would be used. In any event, I think it could
>> be consistent - either labels or values.
>>
>> Is there reason to expect the second case to return the value it did?
>
> Yes, that's how the code is written. Note the reference
> to '1st combination' on the help page.
>
> combn() is not intended for factors; the help page says:
>
>  x    vector source for combinations, or integer n for x <- seq(n).
>
> and factors are not vectors.
>
> Two things will work with factors:
>
> 1. use combn(as.character(yourfactor), m)
> 2. use combn(yourfactor, m, simplify = FALSE) which will return a list.
>
>  -Peter
>
>>
>> This occurs in R 2.10.1
>>
>> Thanks,
>> Greg
>>
>

-- 
Greg Hirson
ghirson at ucdavis.edu

Graduate Student
Agricultural and Environmental Chemistry

1106 Robert Mondavi Institute North
One Shields Avenue
Davis, CA 95616



More information about the R-help mailing list