[R] Creating efficiently a subset of a matrix

Peter Holzer holzer at stat.math.ethz.ch
Fri Feb 11 08:16:17 CET 2000


Dear R-helpers

I have the following problem: given a  m x n matrix A, I want to have just a
m x k submatrix B, with B[i,] = A[i, offset[i] + 1:k], e.g. from

> offset <- c(0, 0, 1)
> a <- matrix(1:9, 3)
> a
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

the submatrix b

1 4
2 5
6 9

I can do this with a for loop or with sapply

> b <- sapply(seq(offset), function(x) a[x,offset[x]+1:2])
## result is transposed

However, comparing the two possibilities on a 10000 x 100 matrix and a
submatrix of 10000 x 50 it turned out (using system.time) that the for loop
was faster (about 20%).

Is there a more efficient way to achieve the desired result?

Thanks, Peter

-- 
____________________________________________________________

Peter Holzer                      phone: + 41 1 632 46 34
Seminar fuer Statistik, LEO C14   fax:   + 41 1 632 12 28
(Leonhardstr. 27)                  <holzer at stat.math.ethz.ch>
ETH (Federal Inst. Technology)
8092 Zurich                       http://www.stat.math.ethz.ch/~holzer/
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list