|
RInside Version 0.2.6
|
00001 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8; -*- 00002 // 00003 // Simple example with data in C++ that is passed to R, processed and a result is extracted 00004 // 00005 // Copyright (C) 2009 Dirk Eddelbuettel 00006 // Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Romain Francois 00007 // 00008 // GPL'ed 00009 00010 #include <RInside.h> // for the embedded R via RInside 00011 00012 Rcpp::NumericMatrix createMatrix(const int n) { 00013 Rcpp::NumericMatrix M(n,n); 00014 for (int i=0; i<n; i++) { 00015 for (int j=0; j<n; j++) { 00016 M(i,j) = i*10 + j; 00017 } 00018 } 00019 return(M); 00020 } 00021 00022 int main(int argc, char *argv[]) { 00023 00024 RInside R(argc, argv); // create an embedded R instance 00025 00026 const int mdim = 4; // let the matrices be 4 by 4; create, fill 00027 R["M"] = createMatrix(mdim); // then assign data Matrix to R's 'M' var 00028 00029 std::string str = 00030 "cat('Running ls()\n'); print(ls()); " 00031 "cat('Showing M\n'); print(M); " 00032 "cat('Showing colSums()\n'); Z <- colSums(M); print(Z); " 00033 "Z"; // returns Z 00034 00035 00036 Rcpp::NumericVector v = R.parseEval(str); // eval string, Z then assigned to num. vec 00037 00038 for (int i=0; i< v.size(); i++) { // show the result 00039 std::cout << "In C++ element " << i << " is " << v[i] << std::endl; 00040 } 00041 exit(0); 00042 } 00043 00044