Skip to content
Prev 236549 / 398500 Next

How to apply vector value function to a multidimensional array indexed by the remaining dimensions?

Hi,
  I am looking for some generalization of colSums and rowSums for general
vector valued functions, and for arrays of more than 2 dimensions. 
  So as a concrete example, suppose I have a 3 dimensional array, given by x
= array(1:100,c(3,4,5)).
and I want to sum the 3rd index of x to obain a 3 by 4 matrix. Using rowSums
would return a vector of length 3 because it treats the last two indices as
a single index. 
  
  Besides summation, let's say if I define a vector valued function
f<-function(x){min(x[1],min(x[2],x[3]))}, and I want to apply f to the last
index of x, meaning for each 1<= i <= 3, 1<=j <=4, I want to compute
f(x[i,j,]), and then put them in a 3 by 4 matrix. How would I be able to do
that without using a for loop? 

  thanks.

  Sincerely,
  John