r语言 - 在Rcpp中用函数变换向量



我在Rcpp中有一个简单的代码问题。我的问题是,我想通过传递给一个函数来改变一个向量。例如:

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

当我在R:

x = rep(-1, 10)
ones(x, length(x))

向量x不变。我怎样才能算出来呢?

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

编辑:在尝试了前两个答案中提出的两种方法后,没有任何变化。

edit:重新启动Rstudio,现在它工作了.......对于Rstudio用户来说这是一个常见的问题吗?

实际上,您可以不通过引用传递,因为Rcpp类是代理对象,但是您必须传递完全正确的vector类型。在您的函数签名中,xIntegerVector,但您传入NumericVector,因为rep(-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
*/ 

同样,如果x在函数签名中类型为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
*/

最新更新