I have a two dimensional matrix that I would like to replicate 10 times to create a three dimensional array where each 'slice' of the array is an identical copy of the two dimensional array.
So, if my 2D array were to be:
a <- matrix(c(1:4),nrow=2)
> a
[,1] [,2]
[1,] 1 2
[2,] 3 4
I would like as output an array like this:
, , 1
[,1] [,2]
[1,] 1 2
[2,] 3 4
, , 2
[,1] [,2]
[1,] 1 2
[2,] 3 4
....
, , 10
[,1] [,2]
[1,] 1 2
[2,] 3 4
I have seen this page (Duplicate matrix to form list), in which the OP was looking to duplicate matrices to a list, which I adapted to then convert to an array:
b<-rep(list(a), 10) # from original post
array(unlist(b), dim = c(nrow(b[[1]]), ncol(b[[1]]), length(b))) # line I added
This works fine but it's a little roundabout - I was wondering if there were a way to do this in one line without going through the creation of a list.
I tried applying the logic of a do.call in the way that is done with rbind to bind multiple rows together, but using abind instead -
do.call(abind,as.list(c(a,a,a,a,a,a,a,a,a,a)))
but the output was one long vector and so not what I was looking for.
Any help is greatly appreciated!
Multidimensional Array in R Last Updated : 22 Apr, 2020 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.
Write a R program to create an 3 dimensional array of 24 elements using the dim () function. v = sample (1:5,24,replace = TRUE) dim (v) = c (3,2,4) print ("3-dimension array:") print (v)
A three-dimensional array can have matrices of different size and they are not necessarily to be square or rectangular. Also, all the elements in an array are of same data type.
A three-dimensional array can have matrices of different size and they are not necessarily to be square or rectangular. Also, all the elements in an array are of same data type. To create a three-dimensional array of different size we would need to use the proper number of rows and columns within the array function.
you can use replicate
, which produces a list by default. To get an array, add simplify = "array".
replicate(10, a, simplify="array")
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 1 3
[2,] 2 4
...
, , 9
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 10
[,1] [,2]
[1,] 1 3
[2,] 2 4
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