[R] Wired behavior of a 2-by-2 matrix indicies

Sarah Goslee sarah.goslee at gmail.com
Sat Feb 26 18:29:05 CET 2011


Hello,

On Sat, Feb 26, 2011 at 12:11 PM, Feng Li <m at feng.li> wrote:
> Dear R,
>
> I found a very wired behavior for a 2-by-2 matrix, see this example
>
>> A <- matrix(1:4, 2)
>> idx4A <- matrix(1:4, 2)
>> A[idx4A]
> Error in A[idx4A] : subscript out of bounds

This shouldn't work. From the help for "[",

          When indexing arrays by ‘[’ a single argument ‘i’ can be a
          matrix with as many columns as there are dimensions of ‘x’;
          the result is then a vector with elements corresponding to
          the sets of indices in each row of ‘i’.

Since there are two dimensions to A, and two rows to idx4A, then this
form is used.
The first row of idx4A is c(1, 3) so the first value extracted is
A[1, 3]
which doesn't exist, thus the error message.

> But other matrices are fine,
>
>> B <- matrix(1:9, 3)
>> idx4B <- matrix(1:9, 3)
>> B[idx4B]
> [1] 1 2 3 4 5 6 7 8 9

The part that surprises me is that this works.
Apparently there is an implicit conversion to vector here because
dim(B) != ncol(idx4B)

What you seem to want is
A[as.vector(idx4A)]
and
B[as.vector(idx4B)]

but you neglected to tell us what you expected the result to be.

Sarah
-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list