Nowadays, there are multiple choices of programming languages. They are nested in one project as is often the case. I once wrote a post about calling C++ from R. Today, I’d like to share a quick way to call R program from Excel (with a few lines of VBA code), which I believe would be useful in many cases.
Background
For background, I was asked to model the competitive rate (“taux concurrentiel”, ou “taux servi moyen” in French) for life savings insurance products. The model had to depend on a historic of interest rates and their moving averages. The first step was to study the correlation of these rates and to figure out which of them are really useful for explaining the competitive rate. The second step was to choose a method to analyse quantitative datas: Principal Component Analysis (PCA) technique was chosen for the task. I didn’t want to implement the PCA from scratch with Excel and VBA. So, I turned to the FactoMineR package in R for help (of course). The rest of the project needed to be done in Excel.
Main steps
Here is the idea and the main steps:
0) Some preliminary works need to be done in the main Excel file for input preparation.
1) An input csv file is then built and saved (with VBA code) in the input folder.
2) Then, I use VBA to call R portable (just a lighter version of R, you can use R instead) and run my R script which is in charge of the PCA analysis. For this step, you need to specify (in the Excel file) where to find R portable and your R script. We also assume that the FactoMineR package has been installed.
3) The output (some graphs built with R) will be saved in the output folder at the end of the R script run.
4) Finally, the VBA code will copy all these graphs and paste them back into the main Excel file.
R script
VBA
You can take a look at the project skeleton here. (The input csv file is assumed to be already available in the input folder).