How to index an R matrix without accessing a vector

I declared a matrix A 1 by 6, saying:

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

Then I do dim (A), and as expected, I get 1 by 6 ... but then I do A [, 2: 5], and I would expect this to be a 1 by 4 matrix with 2 positions, 3,4,5 ... but instead, dim (A [, 2: 5]) gives me NULL! it degraded into a vector or something like that. How can i avoid this?

I end up trying to do something like:

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

by changing a and b, so I can only multiply parts of these matrices together ... but it breaks when A splits into a vector ...

thanks

+6
source share
1 answer

Use ,drop=FALSE as an optional (final) argument to include ] .

Example:

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

This may be the main FAQ, but for compatibility reasons, the behavior is unlikely to change.

+9
source

Source: https://habr.com/ru/post/906889/


All Articles