RInside Version 0.2.10
inst/examples/standard/rinside_sample4.cpp
Go to the documentation of this file.
00001 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
00002 //
00003 // Another simple example inspired by an r-devel mail by Abhijit Bera
00004 //
00005 // Copyright (C) 2009 Dirk Eddelbuettel 
00006 // Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois
00007 
00008 #include <RInside.h>                    // for the embedded R via RInside
00009 #include <iomanip>
00010 
00011 int main(int argc, char *argv[]) {
00012     
00013     try {
00014         RInside R(argc, argv);          // create an embedded R instance 
00015 
00016         std::string txt = 
00017             "suppressMessages(library(fPortfolio)); "
00018             "lppData <- 100 * LPP2005.RET[, 1:6]; "
00019             "ewSpec <- portfolioSpec(); " 
00020             "nAssets <- ncol(lppData); ";
00021         R.parseEvalQ(txt);              // prepare problem
00022         
00023         const double dvec[6] = { 0.1, 0.1, 0.1, 0.1, 0.3, 0.3 }; // choose any weights
00024         const std::vector<double> w(dvec, &dvec[6]);
00025         R["weightsvec"] = w;            // assign weights
00026         txt = "setWeights(ewSpec) <- weightsvec";
00027         R.parseEvalQ(txt);              // evaluate assignment
00028 
00029         txt = 
00030             "ewPf <- feasiblePortfolio(data=lppData, spec=ewSpec, constraints=\"LongOnly\");"
00031             "print(ewPf); "
00032             "vec <- getCovRiskBudgets(ewPf@portfolio)";
00033         Rcpp::NumericVector   V(     (SEXP) R.parseEval(txt) ); 
00034         Rcpp::CharacterVector names( (SEXP) R.parseEval("names(vec)"));   
00035 
00036         std::cout << "\n\nAnd now from C++\n\n";
00037         for (int i=0; i<names.size(); i++) {
00038             std::cout << std::setw(16) << names[i] << "\t"
00039                       << std::setw(11) << V[i] << "\n";
00040         }
00041         
00042     } catch(std::exception& ex) {
00043         std::cerr << "Exception caught: " << ex.what() << std::endl;
00044     } catch(...) {
00045         std::cerr << "Unknown exception caught" << std::endl;
00046     }
00047 
00048     exit(0);
00049 }
00050 
 All Classes Files Functions Variables Enumerations Enumerator Defines