![](/img/trans.png)
[英]How do you convert a vector of vectors containing doubles in C++ to a matrix in R using the Rcpp library?
[英]how can I convert vector of vector as matrix in R using Rcpp
Rcpp的新手在这里。 我在C ++中有一个向量列表,其中我使用向量表示一个矩阵,大小为Mi x N
,其中i
从1 to K
, K
是列表中元素的数量:
std::map<double, vector<vector<double> > x;
换句话说,对于列表的元素1,向量的向量的尺寸为M1 x N
,对于列表的元素2,向量的向量的尺寸为M2 x N
,...,向量的向量的尺寸为列表元素K
的MK x N
。
如何将其转换为R中的矩阵列表。如果尝试:
return wrap(x)
我得到向量列表的列表,而不是矩阵列表。
这是一个示例示例,其中C ++中的x
为:
1st element of map:
within that, element of the 1st vector: 1 1 1 1
element of the 2nd vector: 1 1 1 1
element of the 3rd vector: 2 2 2 2
element of the 4th vector: 3 3 3 3
2nd element of map:
within that, element of the 1st vector: 4 4 4 4
element of the 2nd vector: 3 3 3 3
element of the 3rd vector: 2 2 2 2
element of the 4th vector: 5 5 5 5
element of the 5th vector: 1 1 1 1
如果我尝试return wrap(x)
我会得到R(下面添加了ps额外的缩进以使R的输出更清晰):
$`1`
$`1`[[1]]
[1] 1 1 1 1
$`1`[[2]]
[1] 1 1 1 1
$`1`[[3]]
[1] 2 2 2 2
$`1`[[4]]
[1] 3 3 3 3
$`2`
$`2`[[1]]
[1] 4 4 4 4
$`2`[[2]]
[1] 3 3 3 3
$`2`[[3]]
[1] 2 2 2 2
$`2`[[4]]
[1] 5 5 5 5
$`2`[[5]]
[1] 1 1 1 1
我想在R中返回的是:
$`1`
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 2 2 2 2
[4,] 3 3 3 3
$`2`
[,1] [,2] [,3] [,4]
[1,] 4 4 4 4
[2,] 3 3 3 3
[3,] 2 2 2 2
[4,] 5 5 5 5
[5,] 1 1 1 1
在RCpp中,最有效的方法是什么?
这是您的设计选择: 我正在使用向量的向量来表示矩阵 。 因此,也许您必须为自己编写一个转换器。 由于您是这里的相对频繁发布者,因此您现在肯定已经知道我们有如何在小插图Rcpp-extending中编写您自己的wrap()
函数的文档 。
如果要避免这种情况,我的建议是在需要matrix时实际使用matrix类 。 Rcpp在NumericMatrix中有一个。 RcppArmadillo和RcppEigen着重介绍矩阵代数。
对我来说,RcppArmadillo提供了功能和易用性的完美结合。 如果您想在R之外重用C ++代码,还可以让您编写仅依赖Armadillo标头的代码,但是由于Rcpp / RcppArmadillo,可以非常轻松地将其连接到R。
vector<vector<>>
不携带矩形信息。 我建议您使用自己的类MyMatrixClass
或其他任何类,如果MyMatrixClass
,它们可以很好地容纳vector<vector<>>
。
但是您定义MyMatrixClass::operator SEXP()
以便将其转换为适当的结构。 例如,您可以利用NumericMatrix
类。
wrap
会利用其在编译时所拥有的信息来尽其所能,并且它不知道所有向量都具有相同的大小,因此,所能做的最好的事情就是列出一个数字向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.