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.
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.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With