Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 as.data.frame(as.table). This this my code:

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

I`m getting this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in netfun.nulls.qs[, , i] <- as.data.frame(as.table(nulls.qs[, ,  : 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) as.data.frame(as.table(x)))

Your first entry will look like this:

head(netfun.nulls.qs[[1]])
#>   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 as.data.frame(table(x)) 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(as.data.frame(as.table(x))), simplify = FALSE)
})

do.call(abind::abind, c(netfun.nulls.qs, along = 3))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading