How to create and bind an empty multidimensional array
You can define an empty array for example in this way:
empty <- array(numeric(),c(2,3,0))
Note that you need to set at least one dimension to zero, otherwise the array will contain something by definition. Think for example to a matrix, if you define both dimensions greater than zero, you automatically instantiate a rectangular structure and it cannot be empty, at most it can be filled by NAs.
That being said, abind
works like rbind/cbind
but in a generalized way.
So, as rbind/cbind
add a 1-dimensional structure to a 2-dimensional one, using abind
with a 3-dimensional array, you need to add a 2-dimensional structure to the original array, since you want to append a new structure to a chosen dimension.
Here's an example of abind
usage starting from a 3-dimensional empty array:
Create an empty array 2 x 3 x 0 :
a <- array(numeric(),c(2,3,0))
> a
<2 x 3 x 0 array of double>
[,1] [,2] [,3]
[1,]
[2,]
Append a matrix (or a 2-dim array if you prefer) to the 3rd dimension of the array obtaining a new array 2 x 3 x 1 :
a <- abind(a, matrix(5,nrow=2,ncol=3), along=3)
> a
, , 1
[,1] [,2] [,3]
[1,] 5 5 5
[2,] 5 5 5
Append a matrix again (or a 2-dim array if you prefer) to the 3rd dimension of the previous array obtaining a new array 2 x 3 x 2 :
a <- abind(a, matrix(7,nrow=2,ncol=3), along=3)
> a
, , 1
[,1] [,2] [,3]
[1,] 5 5 5
[2,] 5 5 5
, , 2
[,1] [,2] [,3]
[1,] 7 7 7
[2,] 7 7 7
and so and so forth...
Comments
-
Bobe Kryant almost 2 years
I want to create a empty multidimensional array and then bind it to an existing array.
If my array was not empty, I can bind it with the
abind
package:library(abind) c=matrix(0,2,3) test=array(0,c(2,3,1)) test2=abind(test,c,along=3) test2 #exactly what I expected , , 1 [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 0 0 , , 2 [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 0 0
Now I want to do the same thing except instead of two full arrays, I want one of them to be empty. Here is what would happen if I had characters:
test3=character() #this is empty test3=c(test3,'hi') #I bind the word hi to it test3 [1] "hi"
This does not exactly work if I try to use arrays:
empty=array() abind(empty,test,along=3) Error in abind(empty, test, along = 3) : 'X1' does not fit: should have `length(dim())'=3 or 2
So I am assuming that
array()
is not how you create an empty multidimensional array.Note the differences between the two commands:
empty=array() > empty [1] NA test3=character() > test3 character(0)