[R] General indexing in multidimensional arrays
David Winsemius
dwinsemius at comcast.net
Mon Aug 1 17:41:08 CEST 2011
On Aug 1, 2011, at 10:50 AM, Duncan Murdoch wrote:
> On 11-08-01 5:38 AM, Jannis wrote:
>> Dear R community,
>>
>>
>> I have a general question regarding indexing in multidiemensional
>> arrays.
>>
>> Imagine I have a three dimensional array and I only want to extract
>> on
>> vector along a single dimension from it:
>>
>>
>> data<- array(rnorm(64),dim=c(4,4,4))
>>
>> result<- data[1,1,]
>>
>> If I want to extract more than one of these vectors, it would now
>> really
>> help me to supply a logical matrix of the size of the first two
>> dimensions:
>>
>>
>> indices<- matrix(FALSE,ncol=4,nrow=4)
>> indices[1,3]<- TRUE
>> indices[4,1]<- TRUE
>>
>> result<- data[indices,]
Is this the right answer?
> result<- which(indices, arr.ind=TRUE)
> result
row col
[1,] 4 1
[2,] 1 3
> apply(result, 1, function(x) data[x[1], x[2], ])
[,1] [,2]
[1,] 1.62880528 0.7781005
[2,] -0.08861725 -2.1791674
[3,] 0.78242531 -1.0352826
[4,] 1.40012118 -1.2541230
....if so, it should be possible to encapsulate that behavior in a
function.
--
David Winsemius, MD
West Hartford, CT
>>
>> This, however would give me an error. I am used to this kind of
>> indexing
>> from Matlab and was wonderingt whether there exists an easy way to do
>> this in R without supplying complicated index matrices of all three
>> dimensions or logical vectors of the size of the whole matrix?
>>
>> The only way I could imagine would be to:
>>
>> result<- data[rep(as.vector(indices),times=4)]
>>
>> but this seems rather complicated and also depends on the order of
>> the
>> dimensions I want to extract.
>>
>>
>> I do not want R to copy Matlabs behaviour, I am just wondering
>> whether I
>> missed one concept of indexing in R?
>>
>
> Base R doesn't have anything like that as far as I know. The closest
> is matrix indexing: you construct a 3 column matrix whose rows are
> the indices of each element you want to extract.
>
> Possibly plyr or some other package has functions to do this.
More information about the R-help
mailing list