Author

Josh Day

Published

June 10, 2021

Calling R From Julia

Julia’s younger ecosystem sometimes lacks packages for specialized tasks. The solution: leverage R packages directly from Julia through RCall.jl, enabling seamless interoperability between the two languages.

Installation

] add RCall

Running R Code from Julia

Interactive Mode (REPL)

After importing RCall, access the R REPL by typing $. The prompt switches from julia> to R>, allowing native R commands:

using RCall

# type `$` to enter R mode

R> library(ggplot2)

R> data(diamonds)

R> ggplot(diamonds, aes(x=carat, y=price)) + geom_point()

Non-Interactive Mode

The @R_str macro executes R code programmatically:

using RCall

R"y = 2"
Precompiling packages...
    979.1 msQuartoNotebookWorkerTablesExt (serial)
  1 dependency successfully precompiled in 1 seconds
Precompiling packages...
    982.1 msQuartoNotebookWorkerLaTeXStringsExt (serial)
  1 dependency successfully precompiled in 1 seconds
Precompiling packages...
   3774.4 msQuartoNotebookWorkerRCallExt (serial)
  1 dependency successfully precompiled in 4 seconds
RObject{RealSxp}
[1] 2

Sending Julia Variables to R

Using @rput

x = 1

@rput x

R"x"
RObject{IntSxp}
[1] 1

String Interpolation

R"y = $x"

R"1 + $x"

Retrieving R Variables in Julia

Using @rget

R"z = 5"

@rget z

z
5.0

Using rcopy()

robj = R"z"

rcopy(robj)
5.0

Plotting with ggplot2

R"""
library(ggplot2)
data(diamonds)
p <- ggplot(diamonds, aes(x=carat, y=price)) + geom_point()
ggsave('diamonds_plot.png', p, width=6, height=4, dpi=150)
"""

Resources