简体   繁体   English

1 xm矩阵的尺寸?

[英]Dimension of a 1 x m Matrix?

R suprises me almost every day again and again: R几乎每天都一次又一次地让我感到惊讶:

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? R有1xn矩阵的问题或我的错误在哪里?

> 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. BTW:这个循环是我的算法的瓶颈。 Hence, efficient solutions are appreciated. 因此,赞赏有效的解决方案。

Many thanks! 非常感谢!

The default behaviour of [ subsetting is to convert to a simpler structure, if applicable. [ subsetting]的默认行为是转换为更简单的结构(如果适用)。 In other words, once you subset to a 1xn matrix, the object gets converted to a vector. 换句话说,一旦您将1xn矩阵子集化,该对象就会转换为向量。

To change this behaviour, use the drop=FALSE argument to [ : 要更改此行为,请使用drop=FALSE参数[

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 ?"[" 有关更多信息,请参阅?"["

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM