使用Rcpp中的函数更改向量

Mur*_*1lo 1 r rcpp

我在Rcpp中遇到一个简单的代码问题.我的问题是我想通过将一个向量传递给一个函数来改变它.一个例子是:

//[[Rcpp::export]]
void ones(IntegerVector x, int lx){
   int i;
   for(i = 0; i < lx; i++){
       x(i) = 1;
   }
}
Run Code Online (Sandbox Code Playgroud)

我在R做的时候:

x = rep(-1, 10)
ones(x, length(x))
Run Code Online (Sandbox Code Playgroud)

向量x不会改变.我怎么能解决这个问题?

编辑:如果我传递x作为&x如何更改它的值?

编辑:尝试前两个答案中提出的两个方法后没有任何改变.

编辑:重新启动Rstudio,现在它的工作原理.......这是Rstudio用户的常见问题吗?

nru*_*ell 5

实际上,您可以在不通过引用的情况下执行此操作,因为Rcpp类是代理对象,但您必须准确传递正确类型的向量.在你的函数的签名,xIntegerVector的,但你在通过NumericVectorrep(-1, 10)回报numeric,而不是一个integer.由于类型不匹配时,输入必须被强制转换为一个IntegerVector,这意味着一个副本被创建,和原始(numeric向量)中的改性.例如,

#include <Rcpp.h>

// [[Rcpp::export]]
void ones(Rcpp::IntegerVector x, int lx) {
   for (int i = 0; i < lx; i++) {
       x[i] = 1;
   }
}

/*** R

x <- rep(-1, 10)
class(x)
#[1] "numeric"

ones(x, length(x))
x
#[1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

y <- as.integer(rep(-1, 10)) # or, rep(-1L, 10)
class(y)
#[1] "integer"

ones(y, length(y))
y
#[1] 1 1 1 1 1 1 1 1 1 1

*/ 
Run Code Online (Sandbox Code Playgroud)

同样,如果在函数签名x中键入为a NumericVector,则integer不需要强制:

#include <Rcpp.h>

// [[Rcpp::export]]
void ones_numeric(Rcpp::NumericVector x, int lx) {
   for (int i = 0; i < lx; i++) {
       x[i] = 1.0;
   }
}

/*** R

z <- rep(-1, 10)
class(z) 
#[1] "numeric"

ones_numeric(z, length(z))
z
#1] 1 1 1 1 1 1 1 1 1 1

*/
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案 - 自动投掷扳手所以@coatless曾经不正确:`&`只是视觉糖,因为我们处理已经指针的`SEXP`. (2认同)