我正在尝试在循环中更新变量,但收到错误
静态断言失败:无法将类型转换为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;
}
所以我想我的问题是以前我做错了什么?谢谢
是否值得修复是另一种方式。每当我在向量上或与向量一起使用[[compute时,我通常都会接触RcppArmadillo。因此,这是您在RcppArmadillo中首次尝试的最低版本(有效)。
代码#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::ivec fun() {
arma::ivec v{1,2,3,4,5};
for (int k=0; k<3; k++) {
v = arma::cumsum(v);
}
return(v);
}
/*** R
fun()
*/
输出
R> sourceCpp("~/git/stackoverflow/59936632/answer.cpp")
R> fun()
[,1]
[1,] 1
[2,] 5
[3,] 15
[4,] 35
[5,] 70
R>