RCpp:期望出现单值错误

RCpp: expecting a single value error

本文关键字:单值 错误 期望 RCpp      更新时间:2023-10-16

我正在尝试构建一个使用RCpp执行简单卷积的函数包。代码看起来像

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector conv_filter(NumericVector x, NumericVector c){
  int T = x.size();
  int M = (c.size()-1)/2;
  int t, i;    
    NumericVector fx(T);
  for(t=0; t<T; t++){
        for(i=-M; i<M+1; i++){
            if(t+i>=0 && t+i<T){
        fx(t) += c(M+i)*x(t+i);
            }
        }       
    }
    return fx;
}

在采购时工作得很好,但是当构建到包中时,我一直得到错误说"期望单个值"。我想我犯了非常基本的错误,但即使在阅读相关主题后,我也看不出它是从哪里来的。非常感谢您的帮助。

你的程序为我工作:

R> Rcpp::sourceCpp("/tmp/hrcho.cpp")
R> conv_filter(1:4, 4:1)
[1]  7 16 25 24
R> 

使用这个(只是缩进)源代码:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector conv_filter(NumericVector x, NumericVector c){
  int T = x.size();
  int M = (c.size()-1)/2;
  int t, i;    
  NumericVector fx(T);
  for(t=0; t<T; t++){
    for(i=-M; i<M+1; i++){
      if(t+i>=0 && t+i<T){
        fx(t) += c(M+i)*x(t+i);
      }
    }       
  }
  return fx;
}
/*** R
conv_filter(1:4, 4:1)
*/