Using RCall in Julia

Interfacing Julia and R

Posted on April 24, 2016

Julia is a great language for computation. It’s quick to develop in, and execution time is short compared to many other languages. Check out the julia home site to see how Julia compares to other languages (including C, Go, Java, and Python) used for scientific computing. If you want to hear some arguments against Julia, here are some other opinions.

Often when I am working in Julia, I need to use functions in R – mostly for plotting, sometimes to use nice canned stats functions. So, an interface to R is a big plus. RCall in Julia is one tool that allows interface with R. It’s great, except for the documentation is very underwhelming… But no worries, here is a brief demonstration of how to exploit the statistical functionality in R by simply using the RCall package in Julia. I use RCall mostly for plotting figures in R, because so far, no other plotting tools work anywhere as good… Note that there are other tools for interfacing Julia and R. Rif, for instance. However, Rif seems to produce a lot of deprecation warnings. So, I am only talking about RCall.

Quick Reference

  Example Julia Command Notes
Install RCall Pkg.add("RCall")  
Load RCall using RCall  
Execute a statement in R reval("plot(rnorm(10))") or R"plot(rnorm(10))"
Creating an R variable in R R"var <- 123*321" You can later refer to var by R"var". You could manipulate the variable too: R"var / 100"
Create an R Object r_X = RObject([1 2; 4 5; 7 8]) But I really don’t know what this is used for…
Saving an R Function R_plot = R"plot" use it later in Julia: R_plot(x=randn(100),ylab='')
Loading an R Library @rlibrary("maps") or R"library(maps)" Need to have installed the package in R or in Julia by R"install.packages('maps')"
Using the loaded R Library R"map('county')"  
Loading a Julia variable into R @rput X See example below
Putting an R variable into Julia @rget Z See example below

A Brief Example

#= To Install RCall:
using RCall

X = randn(3,2)
b = reshape([2.0, 3.0], 2,1)
y = X * b + randn(3,1)

# Note that X and y are julia variables. @rput sends y and X to R with the same names
@rput y
@rput X

# Fit a model in R
R"mod <- lm(y ~ X-1)"

# If you want to retrieve a variable from R, look at this example
R"z <- y * 3"
@rget z

# In this example, we really need to use reval
R_lm(some_str_expr) = reval(rparse("lm(" * some_str_expr * ")"))
R_summary = R"summary"
R_mod = R_lm("y ~ X-1")

# Finally, plotting. Note that if you don't set ylab and xlab, you'll get a very messy plot...
R_plot = R"plot"
# Now, you can call R_plot in julia quite like you call plot in R