[Rcpp-devel] conditionally created vectors

Kevin Ushey kevinushey at gmail.com
Thu Feb 13 19:29:30 CET 2014


The way around it is to declare 'xx' in the parent scope, and then assign
to it directly, e.g.

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

'Technically', the object 'xx' will be default initialized when declared
like that, but the compiler can optimize that away.

Cheers,
Kevin


On Thu, Feb 13, 2014 at 10:26 AM, Hideyoshi Maeda <hideyoshi.maeda at gmail.com
> wrote:

> So I'm guessing there is no simple export outside of the {} function?
> On 13 Feb 2014, at 18:17, Dirk Eddelbuettel <edd at debian.org> wrote:
>
> >
> > On 13 February 2014 at 17:48, Hideyoshi Maeda wrote:
> > | 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;
> > | }
> >
> > "Scope".
> >
> > You create 'xx' inside the { } and it does not exist outside of those.
> >
> > | 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;
> > |   }
> > | }
> >
> > Try this. It uses RcppArmadillo which has a resize() member function.
> >
> >
> > // [[Rcpp::depends(RcppArmadillo)]]
> >
> > #include <RcppArmadillo.h>
> >
> >
> > // [[Rcpp::export]]
> > arma::colvec f1(std::string typ){
> >  arma::colvec xx;
> >  if (typ=="nc"){
> >    xx.resize(10);
> >  } else {
> >    xx.resize(20);
> >  }
> >  return xx;
> > }
> >
> > Dirk
> >
> > --
> > Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20140213/f6462d72/attachment-0001.html>


More information about the Rcpp-devel mailing list