On 06/15/2016 09:05 PM, peter dalgaard wrote:
On 15 Jun 2016, at 19:37 , Nick Tulli wrote:
I've got a three dimensional array which I pulled from a netcdf file.
The data in array are the humidity values of locations in the United
States over a time period. The three dimensions are [longitude,
latitude, days], 141x81x92. My goal is to find the mean value at each
longitude/latitude over the 92 day period.
I could probably accomplish my goal by running a loop, but I'm sure
that there is a much easier and more efficient way to accomplish the
goal in R. Any suggestions?
Dunno about fast, but the canonical way is apply(A, c(1,2), mean)
For "mean" and "sum", row/colMeans() is pretty fast and efficient. Note
the 'dims' argument; you might also consider the aperm() function before
# create an array
x <- provideDimnames(array(rnorm(141*81*92), c(141, 81, 92)))
names(dimnames(x)) <- c("long", "lat", "days")
# collapse over days
str(rowMeans(x, dims = 2))
# collapse over lat
x_new <- aperm(x, c("lat", "long", "days"))
(A <- array(1:24,c(2,3,4)))
apply(A, c(1,2), mean)
apply(A, c(1,3), mean) >
and provide commented, minimal, self-contained, reproducible code.