在 RCpp 中将 DataFrame 转换为 Matrix 的最佳方法 [英] best way to convert DataFrame to Matrix in RCpp
问题描述
我有一个 RCpp 代码,在其中的一部分代码中,我试图将数据帧转换为矩阵.DataFrame 只有数字(没有字符串或日期).
I have an RCpp code, where in a part of code I am trying to convert a DataFrame to a Matrix. The DataFrame only has numbers (no strings or dates).
以下代码有效:
//[[Rcpp::export]]
NumericMatrix testDFtoNM1(DataFrame x) {
int nRows=x.nrows();
NumericMatrix y(nRows,x.size());
for (int i=0; i<x.size();i++) {
y(_,i)=NumericVector(x[i]);
}
return y;
}
我想知道在 RCpp 中是否有替代方法(即等效于 R 中的 as.matrix
)来做同样的事情,类似于下面的代码(不起作用):
I was wondering if there is alternative way (i.e. equivalent of as.matrix
in R) in RCpp to do the same, something similar to the following code below (which does NOT work):
//[[Rcpp::export]]
NumericMatrix testDFtoNM(DataFrame x) {
NumericMatrix y(x);
return y;
}
* 编辑 *
感谢您的回答.正如 Dirk 所建议的,C++ 代码比两个答案中的任何一个快 24 倍左右,Function
版本比 internal::convert_using_rfunction
版本快 2%.
Thanks for the answers. As Dirk suggested, the C++ code is around 24x faster than either of the two answers and Function
version is 2% faster than the internal::convert_using_rfunction
version.
我最初是在 RCpp 中寻找答案而不打电话给 R.当我发布我的问题时应该说清楚.
I was originally looking for an answer within RCpp without calling R. Should have made that clear when I posted my question.
推荐答案
类似于 Gabor 的版本,你可以这样做:
Similar to Gabor's version, you can do something like this:
#include <Rcpp.h>
using namespace Rcpp ;
//[[Rcpp::export]]
NumericMatrix testDFtoNM(DataFrame x) {
NumericMatrix y = internal::convert_using_rfunction(x, "as.matrix");
return y;
}
这篇关于在 RCpp 中将 DataFrame 转换为 Matrix 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!