RInside Version 0.2.12
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
rinside_sample1.cpp
Go to the documentation of this file.
1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8; -*-
2 //
3 // Simple example with data in C++ that is passed to R, processed and a result is extracted
4 //
5 // Copyright (C) 2009 Dirk Eddelbuettel
6 // Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Romain Francois
7 //
8 // GPL'ed
9 
10 #include <RInside.h> // for the embedded R via RInside
11 
12 Rcpp::NumericMatrix createMatrix(const int n) {
13  Rcpp::NumericMatrix M(n,n);
14  for (int i=0; i<n; i++) {
15  for (int j=0; j<n; j++) {
16  M(i,j) = i*10 + j;
17  }
18  }
19  return(M);
20 }
21 
22 int main(int argc, char *argv[]) {
23 
24  RInside R(argc, argv); // create an embedded R instance
25 
26  const int mdim = 4; // let the matrices be 4 by 4; create, fill
27  R["M"] = createMatrix(mdim); // then assign data Matrix to R's 'M' var
28 
29  std::string str =
30  "cat('Running ls()\n'); print(ls()); "
31  "cat('Showing M\n'); print(M); "
32  "cat('Showing colSums()\n'); Z <- colSums(M); print(Z); "
33  "Z"; // returns Z
34 
35 
36  Rcpp::NumericVector v = R.parseEval(str); // eval string, Z then assigned to num. vec
37 
38  for (int i=0; i< v.size(); i++) { // show the result
39  std::cout << "In C++ element " << i << " is " << v[i] << std::endl;
40  }
41  exit(0);
42 }
43 
44 
Rcpp::NumericMatrix createMatrix(const int n)
int parseEval(const std::string &line, SEXP &ans)
Definition: RInside.cpp:308
int main(int argc, char *argv[])