[R] Choices from a matrix

From: <davidr_at_rhotrading.com>
Date: Sat 07 May 2005 - 05:06:25 EST


Could someone please suggest a more clever solution to the following problem than my loop below?

Given X a 2xN matrix X, and I a k-subset of N, Generate the (2^k)xN matrix Y with columns not in I all zero and the other columns with all choices of an entry from the first or second row of X.

For example, with
X <- matrix(1:8, nrow=2)
I <- c(1,3)

X is
1 3 5 7
2 4 6 8

and Y should be
1 0 5 0
2 0 5 0
1 0 6 0
2 0 6 0

The order of the rows is unimportant.

---
I solved this using a loop over the rows of Y after forming some preliminary matrices. I think it could be improved.

N <- NCOL(X)
k <- length(I)
G <- as.matrix(expand.grid(rep(list(c(1,2)),k)))
Y <- matrix(0,nc=N,nr=NROW(G))

for(i in 1:NROW(G)){
   ind <- rep(1,N)
   ind[I] <- G[i,]
   Y[i,] <- X[array(c(ind,1:N),dim=c(N,2))]
}
Y[,-I] <- 0




David L. Reiner

 
Rho Trading 440 S. LaSalle St -- Suite 620 Chicago  IL  60605
 
312-362-4963 (voice) 312-362-4941 (fax)
 
______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Sat May 07 05:16:14 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:37 EST