简体   繁体   中英

finding max value from multidimensional array in R

I have an array of dim 4x1x4x71x128. The first dim refers to 4 different models. The third dim refers to lower CI, Correlation, Upper CI and p-value.

What I need as output is a new array of dim 1x1x1x71x128 where the first dim refers to the max value of Correlation(3rd dim) among the 4 models(1st dim).

I tried the following:

newarray <- array(NA, c(1,1,1,71,128))
for (i in 1:4) {
  for (j in 1:nrow(array[1,1,1,,])) {
    for (k in 1:ncol(array[1,1,1,,])){
      newarray[i,1,1,j,k] <- max(array[i,1,1,j,k], na.rm = FALSE)
    }
  }
}

This returns me the maximum value not for Correlation but for lower CI. However, when I change operation to:

newarray[i,1,1,j,k] <- max(array[i,1,2,j,k], na.rm = FALSE)

It does not work. I believe I am not looping right but can't seem to figure it out.

Thanks for you help in advance!

x.max <- apply(x , c(3,4,5) , 
                   function(x) 
                     ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE))) 

Solved! Result is of dim 4x71x128 with the 2nd element of 1st dim being the desired output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM