Rcpp将向量复制到向量 [英] Rcpp Copy a vector to a vector
问题描述
我一般都不熟悉Rcpp和C ++编码,因此请原谅我提出一些基本问题。代码的cpp部分是
// test.cpp
#include< Rcpp。 h>
使用命名空间Rcpp;
// [[Rcpp :: export]]
void testRun(){
IntegerVector Grp1 = IntegerVector :: create(1,2,3,4);
IntegerVector Grp2 = IntegerVector :: create(3,4,5,6);
Rf_PrintValue(Grp1);
Grp1 = Grp2;
Rf_PrintValue(Grp1);
Grp2 [3] = Grp2 [3] +1;
Rf_PrintValue(Grp1);
}
当我运行testrun()时,我会得到输出
> Rcpp :: sourceCpp('test.cpp')
> testRun()
[1] 1 2 3 4
[1] 3 4 5 6
[1] 3 4 5 7
当我将 非常感谢! 如注释中所提示,您可以使用 但这将创建一个新的R对象,然后将其分配给 您还可以使用 std :: copy 另一种可能超出顶部的方法是使用 但是给出 FWIW,在 I am new to Rcpp and C++ coding in general, so forgive me for asking basic questions. The cpp part of the code is and when I run testrun(), I get the output When I assign Thanks a lot! As hinted in the comment, you could use but this will create a new R object that then get assigned to You could also just reuse the existing memory from Another way that is perhaps over the top is to use But given FWIW, in
这篇关于Rcpp将向量复制到向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Gr2
分配给 Gr1
时c $ c> Gr1 = Gr2 ,在赋值后更改 Gr1 $ c中的值,更改
Gr2
中的元素$ c>。 IntegerVectors是否有一个函数可以执行类似 Gr1 = Gr2的副本
的功能,或者我应该使用循环来做到这一点。 $ b
Grp1 = clone(Grp2);
Grp1
,因此您需要支付一些内存分配,并且丢弃一些本可以使用的内存,即,为垃圾收集器增加了更多工作。
std :: copy(Grp2.begin(),Grp2.end(),Grp1.begin());
sapply
。像这样:
自动识别= [](double x){return x; };
Grp1 = sapply(Grp2,identity);
Rcpp
不会应用到lambda上,您可能必须定义 identity
在您的函数之外,此方法才可用。
内联双重身份(double x){
return x;
}
Rcpp14
或 Rcpp11
,您只需执行以下操作:
Grp1 = import( Grp2);
// test.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void testRun() {
IntegerVector Grp1 = IntegerVector::create(1,2,3,4);
IntegerVector Grp2 = IntegerVector::create(3,4,5,6);
Rf_PrintValue(Grp1);
Grp1 = Grp2;
Rf_PrintValue(Grp1);
Grp2[3] = Grp2[3]+1;
Rf_PrintValue(Grp1);
}
> Rcpp::sourceCpp('test.cpp')
> testRun()
[1] 1 2 3 4
[1] 3 4 5 6
[1] 3 4 5 7
Gr2
to Gr1
in Gr1 = Gr2
, changing elements in Gr2
after the assignment changes the values in Gr1
as well. Is there a function for IntegerVectors that could do something like Gr1 = copy of Gr2
or should I be using a loop to do that.Grp1 = clone(Grp2) ;
Grp1
, so you pay for some memory allocation and you discard some memory that could have been used, i.e. more work for the garbage collector down the line. Grp1
with std::copystd::copy( Grp2.begin(), Grp2.end(), Grp1.begin() ) ;
sapply
. Something like this: auto identity = [](double x){ return x; } ;
Grp1 = sapply( Grp2, identity );
Rcpp
does not sapply over lambdas, you'd probably have to define identity
outside your function for this approach to be useable. inline double identity(double x){
return x ;
}
Rcpp14
or Rcpp11
, you could simply do: Grp1 = import(Grp2) ;