[Rcpp-devel] conditionally created vectors

Hideyoshi Maeda hideyoshi.maeda at gmail.com
Thu Feb 13 18:48:00 CET 2014


Dear Rcpp-Devel list,

I am relatively new to Rcpp and am struggling to work out why the following code does not compile.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector f1(String typ){
  if(typ=="nc"){
    Rcpp::NumericVector xx(10);
  } else {
    Rcpp::NumericVector xx(20);
  }
  return xx;
}

Basically the function takes in a string input and if its has the value “nc” then it returns a zero string of length 10 and if it doesn’t then it should return a zero vector of length 20. I don’t quite understand why the above code works but the below code does. What do I need to do to make the above code work,  so that I can call xx after the if statement is done?

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector f1(String typ){
  if(typ=="nc"){
    Rcpp::NumericVector xx(10);
    return xx;
  } else {
    Rcpp::NumericVector xx(20);
    return xx;
  }
}


thank

HLM


More information about the Rcpp-devel mailing list