[R] combinations/ indexing a matrix
Michael Friendly
friendly at yorku.ca
Thu Mar 11 22:25:14 CET 2010
For a package application, I want to generate all 1-way, or 2-way, ...
combinations of factors, symbolically, as a matrix.
E.g., all two-way terms among 4 factors.
> factors <- LETTERS[1:4]
> combn(4,2)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 2 2 3
[2,] 2 3 4 3 4 4
But I want to replace the numbers I in the above by factors[I]. I know
I can do this with gtools::combinations:
> t(combinations(4,2,factors))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "A" "A" "A" "B" "B" "C"
[2,] "B" "C" "D" "C" "D" "D"
But I'd prefer not to have to require an extra package if there is a
simpler way using base R, e.g., by indexing
the result of combn() using factors. I tried, among other non-working
things:
> res <- combn(4,2)
> res[] <- LETTERS[1:4]
> res
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "A" "C" "A" "C" "A" "C"
[2,] "B" "D" "B" "D" "B" "D"
right shape, but wrong result. What is the magic incantation here?
--
Michael Friendly Email: friendly AT yorku DOT ca
Professor, Psychology Dept.
York University Voice: 416 736-5115 x66249 Fax: 416 736-5814
4700 Keele Street http://www.math.yorku.ca/SCS/friendly.html
Toronto, ONT M3J 1P3 CANADA
More information about the R-help
mailing list