Tag Archives: interop

Calling R From Julia

By: Josh Day

Re-posted from: https://www.juliafordatascience.com/calling-r-from-julia/

Calling R From Julia

Since Julia has a younger ecosystem, you won't always find the functionality you need for every task.  In those cases, you're left with the choice to either:

  • Implement it yourself.
    • This is great for the Julia community in the long run (especially if you release your work as a package! Please do this!), but you don't always have the time/energy to do so.
  • Use a package in another language.
    • Language wars are boring. You should use all the tools at your disposable. You don't need to stick with Julia for everything (especially since interop is easy!).

Particularly for niche models in the field of statistics, you'll often find R packages that do not have Julia counterparts.  Thankfully, Julia and R work together rather seamlessly through the help of one package.

Introducing RCall.jl

To get started, let's install RCall:

] add RCall

Running R Code from Julia

  • After installing and typing using RCall, you'll have access to the R REPL Mode by typing $.  Your prompt will change from julia> to R>  and now all of your commands will run in R instead of Julia.  You can use it just like a normal R session.
julia> using RCall

# type `$`

R> install.packages("ggplot2")

R> library(ggplot2)

R> data(diamonds)

R> ggplot(diamonds, aes(x=carat, y=price)) + geom_point()
Calling R From Julia
  • If you want to call R from Julia in a non-interactive manner (not from the REPL), you can use @R_str macro:
julia> R"y = 2"
RObject{RealSxp}
[1] 2

Sending Julia Variables to R

  • The @rput macro sends a variable to R and uses the same name.
julia> x = 1
1

julia> @rput x
1

R> x
[1] 1
  • You can interpolate Julia values in @R_str commands as well as the R REPL Mode:
julia> x = 1
1

julia> R"y = $x"
RObject{IntSxp}
[1] 1

R> 1 + $x
[1] 2

Retrieving R Variables in Julia

  • The @rget macro sends a variable from R to Julia and uses the same name.
julia> R"z = 5"
RObject{RealSxp}
[1] 5


julia> @rget z
5.0

julia> z
5.0
  • You can also convert an RObject into the appropriate Julia counterpart with rcopy.
julia> robj = R"z"
RObject{RealSxp}
[1] 5


julia> rcopy(robj)
5.0

🚀 That's It!

You now know the basics of working in R from Julia.  There are deeper depths to dive into on the topic (such as type conversions between R and Julia), but this should give you a start on using your favorite R package together with Julia.

Enjoying Julia For Data Science?  Please share us with a friend and follow us on Twitter at @JuliaForDataSci.

Additional Resources