1

I have a Rcpp function that has an optional argument which is the maturity of a financial instrument. This can be given as a string (e.g. "2y") or as a integer. If no value is given, the function needs to use a default integer. How can I set the default value for that argument?

I have defined the function with a SEXP argument, the code tests if this is a string or not and depending on this transforms that maturity in an actual date in two different ways. However, I cannot set a default value for the SEXP argument. It seems like a basic question but I have googled quite a bit and could not find anything on this.

Date CPPConvertDate(Date ParamDate, SEXP MaturityDate = 1) {
  Date Result ;
  const int type_Matu = TYPEOF(MaturityDate) ;

  if (type_Matu == 16){
   std::string MaturityDate_string = as<std::string>(MaturityDate) ;
   //' DO STUFF
  } else {
   int MaturityDate_int = as<int>(MaturityDate) ;
     //' DO OTHER STUFF

  }
  return (Result) ;
}

Compiler tells me "Cannot initialize a parameter of type SEXP with an R value of type int" so it is pretty clear that I cannot use 1 a default value for MaturityDate. If possible I would like to avoid having two different functions, one with int arguments and one with string argument.

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
JLG
  • 37
  • 6

1 Answers1

2

Listen to the compiler because it is a source of wisdown. SEXP has no assignment from 1 as it is a union type -- which is why we have all those wrap() functions to return a SEXP given all possible inputs.

So if it is a Date, use a date type. I have been doing that in RQuantLib (which after all lead to to Rcpp) for well over a decade. If you need a mixed type for different behaviour then methinks you will have a hard time coming up with a default value either way.

Also: not "RCPP". Rcpp, please.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725