RInside Version 0.2.12
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
rinside_sample4.cpp
Go to the documentation of this file.
1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
2 //
3 // Another simple example inspired by an r-devel mail by Abhijit Bera
4 //
5 // Copyright (C) 2009 Dirk Eddelbuettel
6 // Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois
7 
8 #include <RInside.h> // for the embedded R via RInside
9 #include <iomanip>
10 
11 int main(int argc, char *argv[]) {
12 
13  try {
14  RInside R(argc, argv); // create an embedded R instance
15 
16  std::string txt =
17  "suppressMessages(library(fPortfolio)); "
18  "lppData <- 100 * LPP2005.RET[, 1:6]; "
19  "ewSpec <- portfolioSpec(); "
20  "nAssets <- ncol(lppData); ";
21  R.parseEvalQ(txt); // prepare problem
22 
23  const double dvec[6] = { 0.1, 0.1, 0.1, 0.1, 0.3, 0.3 }; // choose any weights
24  const std::vector<double> w(dvec, &dvec[6]);
25  R["weightsvec"] = w; // assign weights
26  txt = "setWeights(ewSpec) <- weightsvec";
27  R.parseEvalQ(txt); // evaluate assignment
28 
29  txt =
30  "ewPf <- feasiblePortfolio(data=lppData, spec=ewSpec, constraints=\"LongOnly\");"
31  "print(ewPf); "
32  "vec <- getCovRiskBudgets(ewPf@portfolio)";
33  Rcpp::NumericVector V( (SEXP) R.parseEval(txt) );
34  Rcpp::CharacterVector names( (SEXP) R.parseEval("names(vec)"));
35 
36  std::cout << "\n\nAnd now from C++\n\n";
37  for (int i=0; i<names.size(); i++) {
38  std::cout << std::setw(16) << names[i] << "\t"
39  << std::setw(11) << V[i] << "\n";
40  }
41 
42  } catch(std::exception& ex) {
43  std::cerr << "Exception caught: " << ex.what() << std::endl;
44  } catch(...) {
45  std::cerr << "Unknown exception caught" << std::endl;
46  }
47 
48  exit(0);
49 }
50 
void parseEvalQ(const std::string &line)
Definition: RInside.cpp:366
int parseEval(const std::string &line, SEXP &ans)
Definition: RInside.cpp:308
int main(int argc, char *argv[])