Java Mailing List Archive

http://www.r-help.com/

Home » R Help for Statistical Computing »

[R] combinations/ indexing a matrix

Michael Friendly

2010-03-11

Replies: Find Java Web Hosting

Author LoginPost Reply
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

______________________________________________
R-help@(protected)
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.
©2008 r-help.com - Jax Systems, LLC, U.S.A.