Rcpp将向量复制到向量 [英] Rcpp Copy a vector to a vector

查看:134
本文介绍了Rcpp将向量复制到向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般都不熟悉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

当我将 Gr2 分配给 Gr1 时c $ c> Gr1 = Gr2 ,在赋值后更改 Gr1 Gr2 中的元素$ c>。 IntegerVectors是否有一个函数可以执行类似 Gr1 = Gr2的副本的功能,或者我应该使用循环来做到这一点。 $ b

非常感谢!

解决方案

如注释中所提示,您可以使用

  Grp1 = clone(Grp2); 

但这将创建一个新的R对象,然后将其分配给 Grp1 ,因此您需要支付一些内存分配,并且丢弃一些本可以使用的内存,即,为垃圾收集器增加了更多工作。



您还可以使用 std :: copy

  std :: copy(Grp2.begin(),Grp2.end(),Grp1.begin()); 

另一种可能超出顶部的方法是使用 sapply 。像这样:

 自动识别= [](double x){return x; }; 
Grp1 = sapply(Grp2,identity);

但是给出 Rcpp 不会应用到lambda上,您可能必须定义 identity 在您的函数之外,此方法才可用。

 内联双重身份(double x){
return x;
}

FWIW,在 Rcpp14 或 Rcpp11 ,您只需执行以下操作:

  Grp1 = import( Grp2); 


I am new to Rcpp and C++ coding in general, so forgive me for asking basic questions. The cpp part of the code is

// 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);
}

and when I run testrun(), I get the output

> Rcpp::sourceCpp('test.cpp')
> testRun()
[1] 1 2 3 4
[1] 3 4 5 6
[1] 3 4 5 7

When I assign 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.

Thanks a lot!

解决方案

As hinted in the comment, you could use

Grp1 = clone(Grp2) ;

but this will create a new R object that then get assigned to 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.

You could also just reuse the existing memory from Grp1 with std::copy

std::copy( Grp2.begin(), Grp2.end(), Grp1.begin() ) ;

Another way that is perhaps over the top is to use sapply. Something like this:

auto identity = [](double x){ return x; } ;
Grp1 = sapply( Grp2, identity );

But given 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 ;
}

FWIW, in Rcpp14 or Rcpp11, you could simply do:

Grp1 = import(Grp2) ;

这篇关于Rcpp将向量复制到向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆