[R] effective matrix subset

jgarcia at ija.csic.es jgarcia at ija.csic.es
Sun Aug 10 00:51:45 CEST 2008


It seems that this solution provided by Dan (and also available in
SPoetry; I'm sorry I didn't notice it) is the fastest and simplest. I was
using a more standard approach:

V <- t(A)[(0:(nrow(A)-1))*ncol(A)+X],

That wasn't bad, but I was confident that you, R gurus, could outperform
this. This is clearly a much better solution.

Thanks all, and best wishes,
Javier
------




> on 08/09/2008 06:52 AM Dan Davison wrote:
>> On Sat, Aug 09, 2008 at 06:29:59AM -0500, Marc Schwartz wrote:
>>> on 08/09/2008 06:01 AM jgarcia at ija.csic.es wrote:
>>>> Hi;
>>>> If we have a matrix A, and a vector X, where length(X)=nrow(A), and X
>>>> contains a wanted column for each row in A, in row ascending order.
>>>> How
>>>> would be the most effective way to extract the desired vector V (with
>>>> length(V)=nrow(A))?
>>>
>>> A <- matrix(1:20, 4, 5)
>>>
>>>> A
>>>      [,1] [,2] [,3] [,4] [,5]
>>> [1,]    1    5    9   13   17
>>> [2,]    2    6   10   14   18
>>> [3,]    3    7   11   15   19
>>> [4,]    4    8   12   16   20
>>>
>>>
>>> # Create an arbitrary set of indices, one for each row in A
>>> X <- c(2, 5, 1, 4)
>>>
>>>> X
>>> [1] 2 5 1 4
>>>
>>>
>>> Presumably you want:
>>>
>>> V <- c(A[1, 2], A[2, 5], A[3, 1], A[4, 4])
>>>
>>>> V
>>> [1]  5 18  3 16
>>>
>>>
>>> If so, then:
>>>
>>>> sapply(seq(nrow(A)), function(i) A[i, X[i]])
>>> [1]  5 18  3 16
>>
>> Or
>>
>>> A[cbind(seq(nrow(A)), X)]
>> [1]  5 18  3 16
>>
>> Dan
>
> Better (and faster) solution Dan.
>
> I can't blame the lack of coffee on missing that one this morning. I
> have had a full pot already over the past 6 hours, working on shifting
> my internal clock and getting ready to begin my journey to Dortmund
> later tonight...
>
> Safe travels to all who are going.
>
> Marc
>
>



More information about the R-help mailing list