[R] 'apply' for 0 or 1 element member.
Jeff Newmiller
jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Fri Aug 11 05:35:41 CEST 2023
Define
mean0na <- function(x) {
x[ 0 == x ] <- NA
mean( x, na.rm = TRUE )
}
and then use that instead of mean.
On August 10, 2023 7:25:08 PM PDT, ani jaya <gaaauul using gmail.com> wrote:
>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
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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.
--
Sent from my phone. Please excuse my brevity.
More information about the R-help
mailing list