The real weird thing is I wrote "weird" and it comes out "wired"...

The background is that I did a lot of sparse matrices calculations.
Therefore need some indices tweaks, e.g subtract a block from a big matrix.
Then I just create an indicies matrix and use it directly as a vector since
a matrix is just a vector with dimensions attributed in R. I know I can
convert them to a vector but I did not do it anyway.

Thanks for this information!

Feng

On Sat, Feb 26, 2011 at 6:29 PM, Sarah Goslee <sarah.goslee@gmail.com>wrote:

> Hello,
>
> On Sat, Feb 26, 2011 at 12:11 PM, Feng Li <m@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
>



-- 
Feng Li
Department of Statistics
Stockholm University
106 91 Stockholm, Sweden
http://feng.li/

	[[alternative HTML version deleted]]

