[R] combn with factors

Peter Ehlers ehlers at ucalgary.ca
Wed Apr 7 20:40:55 CEST 2010


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
>

-- 
Peter Ehlers
University of Calgary



More information about the R-help mailing list