> 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]]

______________________________________________
R-help@r-project.org mailing list
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.

Reply via email to