Convert the matrices in a 3D array into three-column format


I have a 3D array of dimensions 13 x 15 x 1000, that is, an array of 1000, 13 x 15 matrices, which is called nulls.qs. I want to convert its matrices into three columns format of 195 x 3, to get a 3D array of dimensions 195 x 3 x 1000, called netfun.nulls.qs.

I have created an empty 3D array and I’m trying to fill it with a for loop that converts each matrix by using This this my code:

netfun.nulls.qs <- array(0, dim = c(195,3,1000))
for (i in 1:1000) {netfun.nulls.qs[,,i]<[,,i]))}

I`m getting this error:

Error in netfun.nulls.qs[, , i] <-[, ,  : incorrect number of subscripts

I don’t know where the problem should be. I appreciate any suggestion.

>Solution :

You don’t need an explicit loop here. You can use apply along the third dimension of your array:

netfun.nulls.qs <- apply(nulls.qs, 3, function(x)

Your first entry will look like this:

#>   Var1 Var2 Freq
#> 1    A    A    1
#> 2    B    A    2
#> 3    C    A    3
#> 4    D    A    4
#> 5    E    A    5
#> 6    F    A    6

If you want the result to be a matrix, then you need to remember that a matrix needs to have all the same data type, whereas produces a data frame with two character columns and one numeric column. To get it as an array we would need to do something like:

netfun.nulls.qs <- apply(nulls.qs, 3, function(x) {
  as.matrix(, simplify = FALSE)
}), c(netfun.nulls.qs, along = 3))

Leave a Reply Cancel reply