[R] How to extract from a matrix based on indices in a vector?
Logickle
logickledoug at yahoo.com
Thu Jun 11 22:20:15 CEST 2009
Thanks, guys. I'll take at a look at these solutions. BTW, my apologies, by
A,B,C,D,... I meant "just some real number", not characters "A","B",..., but
I wasn't clear about that. If that effects the solution approach please let
me know, but I don't think it does. Thanks again, Doug
Marc Schwartz-3 wrote:
>
> 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
>
> ______________________________________________
> R-help at 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.
>
>
--
View this message in context: http://www.nabble.com/How-to-extract-from-a-matrix-based-on-indices-in-a-vector--tp23967316p23988270.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list