简体   繁体   English

如何索引R矩阵而不将其恢复为向量

[英]How to index R matrix without it reverting to vector

I declared a 1 by 6 matrix A by saying: 我宣布1乘6矩阵A说:

A <- matrix(1:6, nrow=1)

I then do dim(A) and as expected I get 1 by 6...but then I do A[,2:5] and I would expect that to be a matrix of dimension 1 by 4 with entries 2,3,4,5...but instead dim( A[,2:5] ) gives me NULL! 我然后做暗淡(A)并且按照预期我得到1乘6 ...然后我做A [,2:5]我希望这是一个1×4的矩阵,条目2,3,4 ,5 ......但是暗淡(A [,2:5])给我NULL! it degraded into a vector or something. 它降级为矢量或其他东西。 How can I avoid this? 我怎么能避免这个?

I am ultimately trying to do something like: 我最终会尝试做类似的事情:

A[,a:b] %*% X[a:b,a:b] %*% t(A[,a:b])

varying a and b so I can multiply only parts of the above matrices together..but this breaks when A decays into a vector... 改变a和b所以我只能将上述矩阵的一部分相乘......但是当A衰变成向量时,这会中断......

Thanks 谢谢

Use ,drop=FALSE as an additional (trailing) argument to involving ] . 使用,drop=FALSE作为涉及的附加(尾随)参数]

Example: 例:

R> M <- matrix(1:4,2,2)
R> M[,2]                  ## looses matrix class
[1] 3 4
R> M[,2,drop=FALSE]       ## forced to a n x 1 matrix
     [,1]
[1,]    3
[2,]    4
R> 

This may well be the main FAQ, but for compatibility reasons the behaviour is unlikely to change. 这很可能是主要常见问题,但出于兼容性考虑的行为是不可能改变的。

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

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