0

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!

nitimkc
  • 11
  • 2
  • Did you try `apply(array,c(2,4,5),max)`? – nicola May 20 '16 at 18:56
  • 2
    It will help to have reproducible example with expected results - http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bulat May 20 '16 at 20:38
  • @nicola Unfortunately, the suggested code gives me NA values – nitimkc May 20 '16 at 22:05
  • @ Bulat I tried to reproduce an example with expected results: `testarray <- array(sample(1:16), c(2,1,2,2,2))` `resultarray <- array(c(12,14,13,7), c(1,1,1,2,2))` `testarray[,1,2,,] # to compare results` `resultarray[1,1,1,,] # max value for each grid point` – nitimkc May 20 '16 at 22:06

1 Answers1

1
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.

nitimkc
  • 11
  • 2