[R] How to extract from a matrix based on indices in a vector?

Marc Schwartz marc_schwartz at me.com
Thu Jun 11 02:12:21 CEST 2009


On Jun 10, 2009, at 7:05 PM, William Dunlap wrote:

> Subscripting by a 2-column matrix
>   M[cbind(v, seq_len(ncol(M)))]
> uses much less space (hence time) than making
> the ncol(M) by ncol(M) intermediate matrix just
> to extract its diagonal.  E.g.
>
> test <- function(n, seed) {
>   if (!missing(seed))
>      set.seed(seed)
>   M <- matrix(sample(LETTERS, 2*n, replace = TRUE), 2)
>   v <- sample(2, n, replace=T)
>   t1<-system.time(r1<-M[cbind(v,seq_len(ncol(M)))])
>   t2<-system.time(r2<-diag(M[v, 1:ncol(M)]))
>   list(identical=identical(r1,r2), "time(matrix subscript)"=t1,
> "time(diag(big matrix))"=t2)
> }
>
>> test(100)
> $identical
> [1] TRUE
>
> $`time(matrix subscript)`
>   user  system elapsed
>  0.000   0.000   0.001
>
> $`time(diag(big matrix))`
>   user  system elapsed
>  0.001   0.000   0.001
>
>> test(1000)
> $identical
> [1] TRUE
>
> $`time(matrix subscript)`
>   user  system elapsed
>  0.000   0.000   0.001
>
> $`time(diag(big matrix))`
>   user  system elapsed
>  0.082   0.021   0.103
>
>> test(5000)
> $identical
> [1] TRUE
>
> $`time(matrix subscript)`
>   user  system elapsed
>  0.001   0.000   0.001
>
> $`time(diag(big matrix))`
>   user  system elapsed
>  3.379   0.552   3.932



Nicely done comparison Bill.

Thanks,

Marc




More information about the R-help mailing list