Accessing environments

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)