hrcho
hrcho

Reputation: 35

RCpp: expecting a single value error

I am trying to build a package with a function performing a simple convolution using RCpp. The code looks like

#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;
}

which works fine when sourced, but when built into a package, I keep getting the errors saying "expecting a single value". I guess I have committed very basic mistakes but I cannot see where it comes from even after reading relevant topics. Thanks a lot for your help.

Upvotes: 3

Views: 1567

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368609

Your program works for me:

R> Rcpp::sourceCpp("/tmp/hrcho.cpp")

R> conv_filter(1:4, 4:1)
[1]  7 16 25 24
R> 

using this (just indented) source code:

#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)
*/

Upvotes: 3

Related Questions