Accessing environments

January 3, 2013
By

(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:

#include <Rcpp.h>

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:

checkEnv()
Stooge Nb 2 is: larry
[1] 42

To leave a comment for the author, please follow the link and comment on his blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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.