1

I hope to obtain the percentage of rows with a maximum value of 1 in a 4-dimensional array. I can obtain that information using an apply function for individual values of the 4th dimension, then use cbind to combine all of the output. However, the number of values in the 4th dimension may vary. Is there an efficient way to obtain the output in the desired format without using cbind?

Below is functional code that returns the desired information as separate vectors for each level of the 4th dimension of an array.

set.seed(9345)

A <- 8
B <- 2
C <- 5
D <- 2  # the value of D might change

y2 <- array(rbinom(A*B*C*D, 1, 0.4), dim = c(A, B, C, D))

pA <- colMeans(apply(y2[,,,1], c(1,3), max))
pB <- colMeans(apply(y2[,,,2], c(1,3), max))

pp <- cbind(pA, pB)
pp

#        pA    pB
# [1,] 0.750 0.875
# [2,] 0.625 0.250
# [3,] 0.375 1.000
# [4,] 0.375 0.500
# [5,] 0.625 0.750

Is there an easy way to obtain the equivalent of pp without using cbind on the output pA and pB (maybe a one-liner that incorporates the apply and colMeans functions)? If the number of values in the 4th dimension (D) change then the number of vectors that must be combined with cbind would vary.

Thank you for any suggestions.

2
  • The code you've posted doesn't work without editing. (You set up an object y, but then operate on y2.) If you do y2 <- y, then the resultant matrix isn't as shown. (It instead matches the one in my answer below). Commented Apr 24, 2012 at 23:44
  • Yes, I saw that and fixed it. Sorry about that. Commented Apr 24, 2012 at 23:50

1 Answer 1

4

This should be equivalent, and simpler to boot:

colMeans(apply(y2[,,,], c(1,3,4), max))
#       [,1]  [,2]
# [1,] 0.750 0.875
# [2,] 0.625 0.250
# [3,] 0.375 1.000
# [4,] 0.375 0.500
# [5,] 0.625 0.750
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I am thinking if I use c(1,3,4) I do not need the t(): colMeans(apply(y2[,,,], c(1,3,4), max)).
@MarkMiller -- Thanks for catching that (fixed now). (It was left over from the experiments I'd run when I was puzzling over why c(1,3,4) didn't match your posted results!)

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.