rmultidimensional-arrayapply

Apply function with a vector as second argument


I have the following code, I wish you could explain me what the function apply with c(1,3) as second argument does.

I completely understand the final result, I just don't understand how it works.

The final results gives me the position of the highest value for each row in each component of the array.

set.seed(666)

# Create 3 vectors 
data1 <- sample(c(0:100),100,replace = T)/100
data2 <- sample(c(0:100),100,replace = T)/100
data3 <- sample(c(0:100),100,replace = T)/100

# pass these vectors as input to the array.
#  5 rows,2 columns and 3 arrays
result <- array(c(data1, data2, data3), dim = c(5,2,3))
print(result)

dim(result)
# [1] 5 2 3
apply(result,c(1,3),which.max)

Solution

  • As @zx8754 mentioned.

    We have 3 dim array, i.e.: 5row by 2col matrix, 3 times. c(1, 3) says give me index of max value for per row, and per 3rd dim.

    If I add a fourth dimension to the array, but run the same apply function with c(1,3), the result is the same as it ignores the fourth dimension.