1

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!

4
  • Did you try apply(array,c(2,4,5),max)? Commented May 20, 2016 at 18:56
  • 2
    It will help to have reproducible example with expected results - stackoverflow.com/questions/5963269/… Commented May 20, 2016 at 20:38
  • @nicola Unfortunately, the suggested code gives me NA values Commented May 20, 2016 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 Commented May 20, 2016 at 22:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.