[Rcpp-devel] conditionally created vectors
Hideyoshi Maeda
hideyoshi.maeda at gmail.com
Thu Feb 13 19:26:55 CET 2014
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
More information about the Rcpp-devel
mailing list