是否有任何理由为什么我应该更喜欢Rcpp::NumericVector过std::vector<double>?
例如,下面的两个功能
// [[Rcpp::export]]
Rcpp::NumericVector foo(const Rcpp::NumericVector& x) {
Rcpp::NumericVector tmp(x.length());
for (int i = 0; i < x.length(); i++)
tmp[i] = x[i] + 1.0;
return tmp;
}
// [[Rcpp::export]]
std::vector<double> bar(const std::vector<double>& x) {
std::vector<double> tmp(x.size());
for (int i = 0; i < x.size(); i++)
tmp[i] = x[i] + 1.0;
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
在考虑其工作和基准性能时是等效的.我知道Rcpp提供了糖和矢量化操作,但是如果只是将R的向量作为输入并将向量作为输出返回,那么我使用哪一个会有什么区别吗?std::vector<double>在与R交互时可以使用导致任何可能的问题吗?
使用RcppArmadillo,从R到Rcpp的转换arma::vec就像使用Rcpp和Rcpp一样简单NumericVector.我的项目使用RcppArmadillo.
我不确定要使用什么,NumericVector或者arma::vec?这两者之间的主要区别是什么?什么时候用哪个?使用一个优于另一个是否有性能/内存优势?成员职能的唯一区别是什么?并且,作为一个奖金问题:我应该考虑arma::colvec还是arma::rowvec?
在C++中,我们可以将变量声明为引用.
int a = 10;
int& b = a;
Run Code Online (Sandbox Code Playgroud)
如果我们设置b=15,a也会改变.
我想在Rcpp做类似的事情.
List X = obj_from_R["X"];
IntegerVector x_i = X[index];
x_i = value;
Run Code Online (Sandbox Code Playgroud)
我想X通过在其向量之一中插入一个值来更新R中的对象.上面的代码不起作用,所以我尝试了这个:
IntegerVector& x_i = X[index];
Run Code Online (Sandbox Code Playgroud)
并收到错误.
error: non-const lvalue reference to type 'IntegerVector'
(aka 'Vector<13>') cannot bind to a temporary of type 'Proxy' (aka 'generic_proxy<19>')
Run Code Online (Sandbox Code Playgroud) 我试图采取一个Rcpp::CharacterMatrix并将每一行转换为自己的元素Rcpp::List.
但是,我编写的函数有一个奇怪的行为,其中列表的每个条目对应于矩阵的最后一行.为什么会这样?这是一些指针相关的概念吗?请解释.
功能:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List char_expand_list(CharacterMatrix A) {
CharacterVector B(A.ncol());
List output;
for(int i=0;i<A.nrow();i++) {
for(int j=0;j<A.ncol();j++) {
B[j] = A(i,j);
}
output.push_back(B);
}
return output;
}
Run Code Online (Sandbox Code Playgroud)
测试矩阵:
这是A传递给上述函数的矩阵.
mat = structure(c("a", "b", "c", "a", "b", "c", "a", "b", "c"), .Dim = c(3L, 3L))
mat
# [,1] [,2] [,3]
# [1,] "a" "a" "a"
# [2,] "b" "b" "b"
# [3,] "c" "c" "c"
Run Code Online (Sandbox Code Playgroud)
输出:
上面的函数应该将此矩阵作为输入并返回矩阵行列表,如下所示:
char_expand_list(mat)
# …Run Code Online (Sandbox Code Playgroud)