I am trying to update a variable within a loop but I am receiving the error
static assertion failed: cannot convert type to SEXP
I am trying to reproduce the following R code in Rcpp:
> v = rep(1, 5)
> for(k in 0:3){
+ v = cumsum(v)
+ }
> print(v)
[1] 1 5 15 35 70
I have gone through the following attempts (uncommenting / commenting the relevant chunks of code) but all give the same error. How can I do this and what am I doing wrong please?
#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;
}
EDIT:
Okay, so I have something working (thanks to 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;
}
So I suppose my question is now what I was doing wrong previously? Thanks
cumsum()is used each time---but only on aNumericVector. So if you swap yourIntegerVectorforNumericVector, it works. It should of course also work forIntegerVector.