Accessing environments

January 3, 2013

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

Extending R with C++ code by using Rcpp typically involves function calls by leveraging the existing .Call() interface of the R API. Passing values back and forth is then done in manner similar to programming with functions.

However, on occassion it is useful to access enviroments (such as the global environment). We can also pass environments (which are first-class datatypes for R) around to instantiate the Rcpp class Environment.

Here we illustrating how to access values from the global environment.

First, let us set some values:

someNumber <<- 42
stooges <<- c("moe", "larry", "curly")

We can access these values in a C++ function setup with Rcpp:


using namespace Rcpp;

// [[Rcpp::export]]
int checkEnv() {
    // access the global env.
    Environment env = Environment::global_env();
    CharacterVector v = env["stooges"];
    Rcout << "Stooge Nb 2 is: " << v[1] << std::endl;
    return env["someNumber"];

Running the example yields:

Stooge Nb 2 is: larry
[1] 42

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)