Ben quant
2012-Mar-09 06:32 UTC
[R] index values of one matrix to another of a different size
> Hello, > > Is this the fastest way to use indices from one matrix to reference rows > in another smaller matrix? I am dealing with very big data (lots of columns > and I have to do this lots of times). > > ######sample data ############## > vals = matrix(LETTERS[1:9], nrow=3,ncol=3) > colnames(vals) = c('col1','col2','col3') > rownames(vals) = c('row1','row2','row3') > > vals > col1 col2 col3 > row1 "A" "D" "G" > row2 "B" "E" "H" > row3 "C" "F" "I" > > # this is a matrix of row references to vals above. The values all stay in > the same column but shift in row via the indices. > indx = matrix(c(1,1,3,3,2,2,2,3,1,2,2,1),nrow=4,ncol=3) > > indx > [,1] [,2] [,3] > [1,] 1 2 1 > [2,] 1 2 2 > [3,] 3 2 2 > [4,] 3 3 1 > ############### end sample data #################### > > # my solution > > > matrix(vals[cbind(c(indx),rep(1:ncol(indx),each=nrow(indx)))],nrow=nrow(indx),ncol=ncol(indx)) > [,1] [,2] [,3] > [1,] "A" "E" "G" > [2,] "A" "E" "H" > [3,] "C" "E" "H" > [4,] "C" "F" "G" > > Thanks, > > Ben > > PS - Rui - I thought you may want to see this since I think this will be a > faster way to deal with the issue you were working with me on...although I > don't show how I build the matrix of indices, I think you get the idea. > >[[alternative HTML version deleted]]
Rui Barradas
2012-Mar-09 20:23 UTC
[R] index values of one matrix to another of a different size
Hello, I don't know if it's the fastest but it's more natural to have an index matrix with two columns only, one for each coordinate. And it's fast. fun <- function(valdata, inxdata){ nr <- nrow(inxdata) nc <- ncol(inxdata) mat <- matrix(NA, nrow=nr*nc, ncol=2) i1 <- 1 i2 <- nr for(j in 1:nc){ mat[i1:i2, 1] <- inxdata[, j] mat[i1:i2, 2] <- rep(j, nr) i1 <- i1 + nr i2 <- i2 + nr } matrix(valdata[mat], ncol=nc) } fun(vals, indx) Rui Barradas -- View this message in context: http://r.789695.n4.nabble.com/Re-index-values-of-one-matrix-to-another-of-a-different-size-tp4458666p4460575.html Sent from the R help mailing list archive at Nabble.com.