Skip to content
Prev 69306 / 398530 Next

Choices from a matrix

Thanks, Bert, but when I tried that, I didn't get a matrix:
[[1]]
[1] 1 2 1 2

[[2]]
[1] 5 5 6 6

[[3]]
[1] 1 2 1 2

[[4]]
[1] 5 5 6 6

[[5]]
[1] 0

[[6]]
[1] 0

[[7]]
[1] 0

[[8]]
[1] 0

[[9]]
[1] 1 2 1 2

[[10]]
[1] 5 5 6 6

[[11]]
[1] 1 2 1 2

[[12]]
[1] 5 5 6 6

[[13]]
[1] 0

[[14]]
[1] 0

[[15]]
[1] 0

[[16]]
[1] 0

The matrix is in there, four times in fact. For larger problems, I believe it would be in 2^k times? It is certainly a one-liner, though, so if the matrix could be extracted simply, it could be of use.

Best regards,
David

-----Original Message-----
From: Berton Gunter [mailto:gunter.berton at gene.com] 
Sent: Friday, May 06, 2005 2:49 PM
To: David Reiner <davidr at rhotrading.com>; r-help at stat.math.ethz.ch
Subject: RE: [R] Choices from a matrix

If I understand you correctly, here's one way based on expand.grid().

I is just an index set, and so all you really need to do is generate your
2^k rows from the part of the matrix you're using in the right places via
replacement:  

e.g. newX<-matrix(0, ncol=ncol(X),nrow=2^length(I))
newX[,I]<-expand.grid(as.list(as.data.frame(X[,I]))) 


N.B. I tried to do the this without the explicit as.list() cast, but got an
error message. I would have thought that expand.grid should have recognized
that a data.frame IS a list without the cast.

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box