Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply on a multidimensional array in R

Tags:

r

I am wondering how to use apply on a multidimensional array. I have something like the following:

A <- array(0, c(2, 2, 5)) for(i in 1:5) {   A[, , i] <- matrix(rnorm(4), 2, 2) } 

I would like to take the average of those slices to get a single 2 by 2 matrix. Any way I come up with is pretty kludgy.

I was hoping to be able to use apply, like I would if I wanted the average say of the columns of a matrix:

B <- matrix(rnorm(10), 5, 2) B.mean <- apply(B, 2, mean) 

But this doesn't seem to work the way I think it might with 3D arrays:

A.mean <- apply(A, 3, mean) 

I appreciate your suggestions.

like image 431
TJB Avatar asked Jul 07 '10 17:07

TJB


People also ask

How do you make a multidimensional array in R?

Creating a Multidimensional ArrayAn array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array. A multidimensional array can be created by defining the value of 'dim' argument as the number of dimensions that are required.

How do I apply a function to all columns in R?

Apply any function to all R data frame You can set the MARGIN argument to c(1, 2) or, equivalently, to 1:2 to apply the function to each value of the data frame. If you set MARGIN = c(2, 1) instead of c(1, 2) the output will be the same matrix but transposed. The output is of class “matrix” instead of “data.

What is the apply function in R?

Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.

How do I create a 3 dimensional array in R?

Create 3D array using the dim() function in R We can create a multidimensional array with dim() function. We can pass this dim as an argument to the array() function. This function is used to create an array. Where, data_inputs is the input data that includes list/vectors.


1 Answers

A.mean <- apply(A, c(1,2), mean) 
like image 149
ncray Avatar answered Sep 18 '22 03:09

ncray