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

Henrik Bengtsson hb at stat.berkeley.edu
Sat Oct 2 17:43:31 CEST 2010


apply() is your friend. You can specify more than one dimension in
argument 'MARGIN'.  Example:

> x <- array(1:100,c(3,4,5))

> y <- apply(x, MARGIN=c(2,3), FUN=sum)
> y
     [,1] [,2] [,3] [,4] [,5]
[1,]    6   42   78  114  150
[2,]   15   51   87  123  159
[3,]   24   60   96  132  168
[4,]   33   69  105  141  177

> z <- matrix(0, nrow=4, ncol=5);
> for (ii in 1:3) z <- z + x[ii,,];
> z
     [,1] [,2] [,3] [,4] [,5]
[1,]    6   42   78  114  150
[2,]   15   51   87  123  159
[3,]   24   60   96  132  168
[4,]   33   69  105  141  177
> stopifnot(all.equal(z,y))

/Henrik

On Fri, Oct 1, 2010 at 12:38 PM, yunjiangster <yunjiangster at gmail.com> wrote:
>
> 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
> --
> View this message in context: http://r.789695.n4.nabble.com/How-to-apply-vector-value-function-to-a-multidimensional-array-indexed-by-the-remaining-dimensions-tp2937368p2937368.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list