[R] Plot and curve inside C++

Dirk Eddelbuettel edd at debian.org
Sun Mar 6 15:53:50 CET 2011


On 6 March 2011 at 12:37, Paul Smith wrote:
| Dear All,
| 
| I would like to use
| 
| - plot,
| - curve
| 
| inside a C++ program. What R package do you recommend? Rcpp?

You can use base R, embedding R is explained in the 'Writing R Extensions'
manual.  That said, the material is a little on the advanced side.
Rcpp and RInside try to provide an easier API, and some users find it
helpful.  

As for your question, I am committing the code below as rinside_sample11.cpp
in the examples/standard/ directory of RInside. With the generic Makefile in
that diretory, you just say 'make' and the rinside_sample11 binary results
(as do all the other examples and tests there).

I hope you find it mostly self-explanatory, if not please come to the
rcpp-devel list for help.

Dirk


// Simple example motivated by post from Paul Smith <phhs80 at gmail.com>
// to r-help on 06 Mar 2011
//
// Copyright (C) 2011  Dirk Eddelbuettel and Romain Francois

#include <RInside.h>                    // for the embedded R via RInside

int main(int argc, char *argv[]) {

    // create an embedded R instance
    RInside R(argc, argv);               

    // evaluate an R expression with curve() 
    // because RInside defaults to interactive=false we use a file
    std::string cmd = "tmpf <- tempfile('curve'); "  
                      "png(tmpf); "
                      "curve(x^2, -10, 10, 200); "
                      "dev.off();"
                      "tmpf";
    // by running parseEval, we get the last assignment back, here the filename
    std::string tmpfile = R.parseEval(cmd);

    std::cout << "Could now use plot in " << tmpfile << std::endl;
    unlink(tmpfile.c_str());		// cleaning up

    // alternatively, by forcing a display we can plot to screen
    cmd = "x11(); curve(x^2, -10, 10, 200); Sys.sleep(30);";
    // parseEvalQ evluates without assignment
    R.parseEvalQ(cmd);
    
    exit(0);
}



-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com



More information about the R-help mailing list