[R] Index mapping on arrays
Robin Hankin
r.hankin at noc.soton.ac.uk
Thu Feb 1 15:37:31 CET 2007
Hello Demi
The trick for array indexing
on an array A, where length(dim(A))==n,
is to use an n-column matrix M to extract the elements
by rows of M.
If I understand correctly, the following should help:
> A <- array(1:18,c(3,3,2))
> x <- 2:3
> y <- 1:2
> A[cbind(x,y,1)]
[1] 2 6
You may find the following useful too:
> A[as.matrix(cbind(1,expand.grid(x,y)))]
[1] 4 7 13 16
>
best
rksh
On 1 Feb 2007, at 13:34, Demi Anderson wrote:
> Dear R-community,
>
> I have some trouble with index mappings for arrays. If, for example,
> I have the array
>
> R> A <- array(1:9, c(3,3,2))
>
> and two index mappings both of same size
>
> R> x <- c(2, 3)
> R> y <- c(1, 2)
>
> Now I want to access the elements (A[1, x[i], y[i]])_i of A, i.e.
> A[1, x[1], y[1]] = A[1, 2, 1] and A[1, x[2], y[2]] = A[1, 3, 2].
>
> If I use
>
> R> A[1, x, y]
>
> I would get every combinations of indices of all elements of x and y
> i.e. A[1, x[1], y[1]], A[1, x[1], y[2]], A[1, x[2], y[1]] and A[1,
> x[2], y[2]]. But how can I access the elements (A[1, x[i], y[i]])_i.
> My arrays dimensions are actually large in the second
> component (for example the dimension might be 10*10000*10) so I'm
> looking for a method avoiding loops.
>
> The question is probably trivial for you, but I just could not
> figure it out. So sorry for bugging you and many thanks in advance
> for any help.
>
> Best wishes, Demi Anderson.
> --
> "Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
tel 023-8059-7743
--
This e-mail (and any attachments) is confidential and intend...{{dropped}}
More information about the R-help
mailing list