I am new to StackOverflow, although I played with R. I am struggling with a problem for which I could not find an answer on the site. Please correct me if my searches were not accurate enough.
I have two 3D arrays, in this simplified case 256x256x200. The first is the field, the second is the indices, from 1 to 8. I want to calculate the average value at each vertical level in accordance with the values and calculation of the indices, i.e. An average field for 200 levels for each index (from 1 to 8). This should only be done if there are enough indexes (i.e., the if condition inside the loop). My output should be an 8x200 matrix.
In this example, I create two random arrays. Below is the base code that I use:
nz=200
lev=1:nz
indices=8
var0=array(rnorm(256*256*nz),dim=c(256,256,nz))
octo=array(sample(1:indices,size=256*256*nz,replace=T),dim=c(256,256,nz))
counts=apply(octo,3,function(x) table(factor(x,levels=1:indices)))
thr=0.125
np=length(var0[,1,1])*length(var0[1,,1])
profile=array(NA,dim=c(nz,indices))
t0=proc.time()
for (i in 1:indices)
{
for (z in 1:length(lev))
{
if (counts[i,z]/np>thr)
{v0=var0[,,z]; profile[z,i]=counts[i,z]/np*mean(v0[octo[,,z]==i],na.rm=T)}
}
}
print(proc.time()-t0)
user system elapsed
5.169 0.001 5.170
, , , , "" , (.. octo ). , , .
- ?
!
EDIT: octo, thr. , if , .