It sometimes could be a great idea to incorporate bits of C++ into our R coding through the Rcpp package. Before writing or calling our C++ functions, we need firstly a working C++ setup for R, which is not difficult on Mac OS system.
First, we need a C++ compiler. We can download XCode and install the Command Line Tools. Second, we need to create a file $\sim$/.R/Makevars, to tell R which compliers to use. The file creation can be done by typing the following commands in Terminal,
cd ~/.R
nano Makevars
Now add the following text:
CC = clang
CXX = clang++
And follow the directions at the bottom of the screen to "write out" and close the file (Control-O Enter and Control-X). Next, we need to install Rcpp package in R from source so that it is built with the same C++ complier we are using.
install.packages("Rcpp", type = "source")
After finishing the setup of connection between C++ and R, we can write a C++ function that R can call. This C++ file should have extension .cpp. And we can thus source it into R using sourceCpp(). It will create a matching R function and we can use it with input.
Comments
Post a Comment