[R] indexing an array
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Thu Sep 20 15:00:11 CEST 2001
siim at obs.ee writes:
> Dear everybody,
>
> I have a following problem. I have a 3D array
>
> lambda <- array( dim=c(N,M,M-1))
>
> where I have to extract the elements as follows:
>
> lambda[ 1, state[1], 1]
> lambda[ 1, state[1], 2]
> ...
> lambda[ 1, state[1], M-1]
> lambda[ 2, state[2], 1]
> ...
> lambda[ 2, state[2], M-1]
> ...
> lambda[ N, state[N], M-1]
>
> i.e. the result should be a 2D array, where the second index follows the
> first one and the third is free (lambda[i,state[i],]). The process is
> to be repeated so I do not want to write a cycle.
>
> Any suggestions?
How about
X <- matrix(,N,M-1)
rr <- as.vector(row(M))
cc <- as.vector(col(M))
X[cbind(rr,cc)] <- lambda[cbind(rr, state[rr], cc)]
or (faster)
rr <- rep(1:N, M - 1)
cc <- rep(1:(M - 1), rep(N, M - 1))
X <- matrix(lambda[cbind(rr, state[rr], cc)], N, M - 1)
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list