[R] Averaging specified array indices

Bert Gunter gunter.berton at gene.com
Fri Dec 27 18:11:05 CET 2013


I just wanted to note that Arun's first approach, which uses matrix
indexing -- often a very useful way to do these things, btw -- can be
simplified a bit.

m <- do.call(rbind,xyz_indices) ## 4x3 matrix
## avoids repeated evaluation. lapply is not needed as it's a list already

sapply(seq(dim(edm)[4]), function(i)mean(edm[cbind(m,i)]))

does it.

Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch




On Fri, Dec 27, 2013 at 6:42 AM, arun <smartpink111 at yahoo.com> wrote:
> HI,
>
> You could try:
>
> res1 <- sapply(seq(dim(edm)[4]),function(i) mean(edm[do.call(rbind,lapply(xyz_indices,function(x) c(x,i)))],na.rm=TRUE))
>
> #or
> indx <- cbind(matrix(rep(unlist(xyz_indices),50),ncol=3,byrow=TRUE),rep(1:50,each=4))
> res2 <-tapply(edm[indx],((seq(200)-1)%/%4)+1,mean)
>  dimnames(res2)[[1]] <- NULL
>  identical(res1,as.vector(res2))
> #[1] TRUE
>
>
>
> A.K.
>
>
>
>
>
> On Friday, December 27, 2013 8:31 AM, "Morway, Eric" <emorway at usgs.gov> wrote:
> In the larger problem I'm attempting to solve, I read a 2Gb file
> into a 4D array, where the first 3 dimensions are related to space
> (x, y, z), and the 4th dimension is time.  My goal is to find the
> average of specific x, y, z-indices for each time step.
>
> A small, reproducible example starts like this:
>
> edm <- array(rnorm(20*20*4*50), dim=c(20,20,4,50))
> xyz_indices <- list(c(2,10,1), c(4,5,1), c(6,7,1), c(19,13,1))
>
> What's the best way to calculate the average of the x, y, z
> indices specified in the "xyz_indices" list for each of the 50 time
> steps represented by the 4th dimension of "edm"?  In other words,
> I want to end up with a time series of length 50 where each value of
> the series is the average of the 4 xyz_indices.
>
>
> Eric
>
>     [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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.
>
>
> ______________________________________________
> R-help at r-project.org 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.



More information about the R-help mailing list