Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

r - Dimension of a 1 x m Matrix?

R suprises 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 has 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 to easily fix the initial example, which is close to my actual problem? BTW: This loop is the bottleneck of my algorithm. Hence, efficient solutions are appreciated.

Many thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The default behaviour of [ subsetting is to convert to a simpler structure, if applicable. In other words, once you subset to a 1xn matrix, the object gets converted to a vector.

To change this behaviour, use the drop=FALSE argument to [:

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 ?"["


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...