Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Extend a multi-dimensional array

Tags:

r

I have a multidimensional array S:

> dim(S)
[1] 45 81  3 52

I would like to add one column in the third dimension to have:

> dim(S)
[1] 45 81  **4** 52

and preserve all the current data in S where they are.

like image 803
Timothée HENRY Avatar asked Mar 26 '14 13:03

Timothée HENRY


People also ask

Can Matrix have more than 2 dimensions in R?

Arrays are the R data objects which can store data in more than two dimensions. For example: If we create an array of dimensions (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays.

How do I increase dimensions in R?

In general, dim(m) = c(dim(m), 1) will add a dimension to m (need to start with 2 at least, vectors only have length, not dimension). But if you want the new dimension to go in the middle somewhere you'll have to specify or define some logic for where it goes. then a=function(x){ if(!is.

How do you add to an array in R?

Creating an Array An array in R can be created with the use of array() function. List of elements is passed to the array() functions along with the dimensions as required. dimnames : Default value = NULL. Otherwise, a list has to be specified which has a name for each component of the dimension.

Can arrays have more than two dimensions?

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns. Similarly, you can declare a three-dimensional (3d) array.


2 Answers

Here is one potential base R solution with [<-.

S.new <- array(NA, dim=c(45, 81, 4, 52))
S.new[,,-4,] <- S                 # re-insert on all but the added extent

Basically, you just re-insert into your new array but by specifying the dimensions that exist in your old array.


We can test with a small toy example to see that it works::

arr <- array(rep(1:4, each=4), dim=c(2, 2, 2, 2))     # toy array
arr.new <- array(NA, dim=c(2, 2, 3, 2))               # increased dimension 3

And then one simple step does it:

arr.new[,,-3,] <- arr
like image 84
BrodieG Avatar answered Oct 04 '22 15:10

BrodieG


If you load in the abind package, you have access to

empty <- array(0, dim=c(45,81,52))
S <- abind(S,empty, along=3)
like image 41
Gavin Kelly Avatar answered Oct 04 '22 15:10

Gavin Kelly