Intro

The objective behind this post is to provide users with information on how to associate a compiler with the OS X version of R. This has been a bit problematic for many R users since OS X Mavericks, which resulted in gfortran binaries being dropped from the R installer. More curiously, the additional demand to have access to a compiler vs. downloading a binary from CRAN became apparent slightly after Rcpp’s 0.10.0 version, when attributes where added that removed the necessity to use R’s SEXP objects.

Install Guide

The guide mandates the use of scripting commands via Terminal.app found in /Applications/Utilities/. Terminal is OS X’s equivalent to Linux’s shell and Window’s command line. From terminal, we will install XCode Command Line Tools and then install the gfortran used to compile R. There are four commands in total that will need to be entered via Terminal.

XCode Command Line Tools

  1. Open the Terminal from /Applications/Utilities/
  2. Type the following into Terminal
xcode-select --install
  1. Press “Install”
  2. Verify installation by typing into terminal:
gcc --version

Install an R Specific gfortran tools

  1. Open the Terminal from /Applications/Utilities/
  2. Type the following into Terminal
curl -O http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2
sudo tar fvxz gfortran-4.8.2-darwin13.tar.bz2 -C /

Quick check

To verify that everything is working appropriately, let’s do a quick C++ program using Rcpp.

First, let’s install Rcpp within R.

install.packages('Rcpp')

Create a new file, name the follow: helloworld.cpp

By adding the .cpp extension, the file is viewed as being C++ code.

Within the file write:

#include <Rcpp.h>   

// [[Rcpp::export]]
void hello_world() {
  Rcpp::Rcout << "Hello World!" << std::endl;  
}

// After compile, this function will be immediately called using
// the below snippet and results will be sent to the R console.

/*** R
hello_world() 
*/

Compile the function using:

Rcpp::sourceCpp('~/path/to/file/helloworld.cpp')

where 'path/to/file/' is the location containing helloworld.cpp

If everything is installed appropriately, then you should see the following in the console:

> hello_world()

Hello World!

In addition, you should have a new function within the global environment scope called “hello_world”. You can call this function like a normal R function via:

hello_world()