在循环中更新变量

Update a variable within a loop

我正在尝试更新循环中的变量,但收到错误消息

static assertion failed: cannot convert type to SEXP

我正在尝试在 Rcpp 中重现以下 R 代码:

> v = rep(1, 5)
> for(k in 0:3){
+   v = cumsum(v)
+ }
> print(v)
[1]  1  5 15 35 70

我进行了以下尝试(取消注释/注释相关代码块)但都给出了相同的错误。我该怎么做,请问我做错了什么?

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector fun() {

  IntegerVector v = rep(1, 5);

  // Attempt 1. 
  for(int k = 0; k < 4; ++k){
    v = cumsum(v);
  }

  // Attempt 2.
  // IntegerVector tempv;
  // for(int k = 0; k < 4; ++k){
  //   tempv = cumsum(v);
  //   v = tempv;
  // }

  // can reproduce error more simply with the following: 
  // so issue is assigning back to variable or change of class?
  // v = cumsum(v);

  // Attempt 3.
  // IntegerVector tempv;
  // for(int k = 0; k < 4; ++k){
  //   tempv = cumsum(v);
  //   v = as<IntegerVector>(tempv);
  // }  

  return v;
}

编辑:

好的,所以我有一些东西正在工作(感谢this

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector fun() {

  IntegerVector v = rep(1, 5);
     for(int k = 0; k < 4; ++k){
        std::partial_sum(v.begin(), v.end(), v.begin());
     }
   return v;
}

所以我想我现在的问题是我之前做错了什么?谢谢

正如我在之前的评论中暗示的那样,这应该有效。事实并非如此,您发现了一个错误。

是否值得修复是另一种方式。每当我 计算 或使用向量时,我通常会使用 RcppArmadillo。所以这是你第一次尝试的最小(工作)版本,在 RcppArmadillo 中。

代码

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::ivec fun() {
  arma::ivec v(5, arma::fill::ones);

  for (int k=0; k<3; k++) {
    v = arma::cumsum(v);
  }

  return(v);
}

/*** R
fun()
*/

输出

R> sourceCpp("~/git/Whosebug/59936632/answer.cpp")

R> fun()
     [,1]
[1,]    1
[2,]    4
[3,]   10
[4,]   20
[5,]   35
R> 

编辑

进行了一个小修复,并通过调用 ones 来替换早期的 C++11 curly-init 以复制 rep(1,5).