[R] 'apply' for 0 or 1 element member.

ani jaya g@@@uu| @end|ng |rom gm@||@com
Fri Aug 11 04:25:08 CEST 2023


Hello,

I try to calculate the mean of an array with a condition. My array is
B=c(181,101,420) in dimensions. And I want to find a specific member
in 3rd dimension (time monthly) based on a condition of another data
frame, A =c(420). My final array would be C=c(181,101,12) which 12 is
a monthly mean based on the condition of A.

what I tried is below but doesn't work.

#find the index with a condition larger than 0.5
index<-which(A>=0.5)
#convert the index to monthly
index1<-index%%12
#change 0 to 12 (Jan=1, Feb=2, and so on..)
index1[index1==0]<-12

for (i in 1:12){
dummy<-index[which(index1==i)]
C[,,i]<-apply(B[,,dummy],c(1,2), mean,na.rm=T)
}

The problem is when there is a month that doesnt meet the condition,
it will return 0 element.

apply(B[,,1],c(1,2), mean,na.rm=T) also produce an error.

Any solution and turnaround would be appreciated.

Thank you

Ani Jaya



More information about the R-help mailing list