The dimension of the matrix is ​​1 x m?

R surprises me almost every day again and again:

m <- matrix( 1:6, ncol=2 ) while( dim(m)[1] > 0 ){ print(m); m <- m[-1,] } 

gives:

  [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 [,1] [,2] [1,] 2 5 [2,] 3 6 Error in while (dim(m)[1] > 0) { : argument is of length zero 

Does R have a problem with 1xn matrices or where is my mistake?

 > nrow( m[-c(2,3), ] ) NULL > dim( m[-c(2,3), ] ) NULL > m[-c(2,3), ][,1] Error in m[-c(2, 3), ][, 1] : incorrect number of dimensions > str( m[-c(2,3), ] ) int [1:2] 1 4 

Any idea how easy it is to fix the original example that is close to my real problem? BTW: This loop is the bottleneck of my algorithm. Therefore, effective decisions are made.

Many thanks!

+3
source share
1 answer

Substitution behavior [ default is a conversion to a simpler structure, if applicable. In other words, after you multiply with a 1xn matrix, the object is converted to a vector.

To change this behavior, use the drop=FALSE argument in [ :

 m <- matrix( 1:6, ncol=2 ) while( dim(m)[1] > 0 ){ print(m); m <- m[-1, , drop=FALSE] } [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 [,1] [,2] [1,] 2 5 [2,] 3 6 [,1] [,2] [1,] 3 6 

For more information, see ?"["

+8
source

All Articles