[R] Large 3d array manipulation
murdoch at stats.uwo.ca
Sat Feb 28 01:49:49 CET 2009
On 27/02/2009 6:15 PM, Vemuri, Aparna wrote:
> I have a large 3 dimensional array of size (243,246,768)
> The first dimension is Rows, second is columns and the third is Time.
> So for each row and column, I want to calculate the mean of time steps
> 1:8, 2:9, 3:10 and so on and assign the values to a new array. For this
> I am using the following script.
> for(i in 1:243)
> for(j in 1:246)
> for(k in 1:768)
> newVar[i,j,k] <- mean( myVar[i,j,k:k+7])
> This works, but needless to mention it take a very long time to loop
> over all the rows, columns and time periods. I was wondering if there is
> a simpler way to do this.
Yes, vectorize it. I think this would work:
newVar <- array(NA, c(243, 246, 768))
for (k in 1:768)
newVar[,,k] <- apply(myVar, 1:2, function(x) mean(x[k:(k+7)]))
but of course I haven't tried it.
More information about the R-help