Home > Software engineering >  R treats multidimensional array as one dimensional
R treats multidimensional array as one dimensional

Time:09-15

R seems to treat multidimensional array as one single array. Is there a way to loop through the array and keep the structure in it?

It seems that I couldn't only use for i in 1:length(...) either, I'll need to know the dimension of the array at all time as length just returns the total size. Is c not the correct function to use here? Thanks.

components = array(c( c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
                       c(0, 1, 0, 1, 0, 1, 0 ,1, 0, 1),
                       c(0, 0, 1, 0, 0, 1, 0 ,0, 1, 0),
                       c(0, 1, 1, 1, 1, 1, 1, 1, 1, 1)), dim=c(4,10) )
components
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    0    0    0    0    0    0    1    1     1
[2,]    0    0    0    1    1    0    1    0    1     1
[3,]    0    0    0    0    0    1    0    0    1     1
[4,]    0    0    1    1    1    0    0    1    1     1
for( component in components ){ print(component) }
[1] 1
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 1
[1] 0
[1] 1
[1] 0
[1] 1
[1] 0
[1] 1
[1] 0
[1] 1
[1] 0
[1] 0
[1] 1
[1] 0
[1] 0
[1] 1
[1] 0
[1] 0
[1] 1
[1] 0
[1] 0
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
> length(components)
[1] 40

CodePudding user response:

You can iterate along each dimension in its own loop. If you don't know the length of the dimensions, use dim

For example, suppose we just want to print each number one at a time to the console in an array format:

components = array(c( c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
                      c(0, 1, 0, 1, 0, 1, 0 ,1, 0, 1),
                      c(0, 0, 1, 0, 0, 1, 0 ,0, 1, 0),
                      c(0, 1, 1, 1, 1, 1, 1, 1, 1, 1)), dim=c(4,10) )

for(i in 1:dim(components)[1]) {
  for(j in 1:dim(components)[2]) {
    cat(components[i, j], " ")
  }
  cat("\n")
}
#> 1  0  0  0  0  0  0  1  1  1  
#> 0  0  0  1  1  0  1  0  1  1  
#> 0  0  0  0  0  1  0  0  1  1  
#> 0  0  1  1  1  0  0  1  1  1

Created on 2022-09-14 with reprex v2.0.2

CodePudding user response:

You can process rows with a slight modification of your code:

for( component in seq(nrow(components)) ){ print(components[component, ]) }

If the output is a vector you can convert it back to the original matrix dimensions with

x <- print(c(components))
dim(x) <- dim(components)
  • Related