1维矩阵变为R中的向量

Jon*_*ona 11 r vector matrix rcpp

> a<-matrix(c(1:9),3,3)
> a
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> a[3,]*a[,3]  # I expect 1x1 matrix as result of this.
[1] 21 48 81
> class(a)
[1] "matrix"
> class(a[3,])
[1] "integer"
Run Code Online (Sandbox Code Playgroud)

在R中,1维矩阵变为向量.我可以避免这个吗?我想保留1-D矩阵作为矩阵.实际上,我需要向RcppArmadillo抛出许多种矩阵,甚至是零D矩阵.将矩阵单独更改为向量是我的问题.

jor*_*ran 17

这是一个R FAQ.你需要这样做a[3,,drop = FALSE].


Jos*_*ich 9

你会混淆元素乘法和矩阵乘法(参见参考资料?"*").你想要%*%:

> a[3,]%*%a[,3]
     [,1]
[1,]  150
Run Code Online (Sandbox Code Playgroud)