How to link R and Julia code

Share

Julia is a powerful, high-level, dynamic programming language. It is also a general-purpose language used to write applications. It has many features like being open-source, simple, efficient, and fast. But one feature that makes it stand out is interoperability.

What is interoperability?

Interoperability can be described as the capacity of two or more languages to interact with each other for effective data transmission in any system. One of Julia’s features is its ability to communicate and call language into itself while writing the Julia syntax.

How can we link R and Julia code?

To inter-operate with the R language, the RCall package is used. This package is built by Julia Interop.This is a GitHub organization that has produced several useful packages for integrating Julia with other languages. This package facilitates communication between R and Julia, allowing you to execute R code within Julia scripts or notebooks and vice versa. By incorporating the RCall package, we can harness the strengths of both languages, enhancing the flexibility and capabilities of the data analysis or scientific computing workflows.

Code example

Let's look at the following example:

using RCall
@rlibrary stats

N = 10
x = 1:10
mean = 10
sd = 5

a = R"rnorm($N, mean=$mean, sd=$sd)"
y = dlnorm(x, meanlog=mean, sdlog=sd)

println("List of random numbers")
for i = 1:length(a)
    println("$i \t $(a[i])")
end

println("\nLog normal probability density function")
println(y)
Executing R code in Julia

Explanation

  • Line 1: The RCall library is imported in the Julia file.

  • Line 2: The R library stats is imported in Julia using the @rlibrary macro.

  • Lines 4–7: Different variables are defined in Julia which will be used for random number generation and a log-normal probability density function.

  • Line 9: An R script is used to generate random numbers with N values, a mean of mean, and a standard distribution of sd.

  • Line 10: The R function stats.dlnorm() is used to generate a log-normal probability density function with the independent variable array x, a log mean of mean, and a log standard distribution of sd.

  • Lines 12–18: The resulting arrays are printed.

Note: If you want to learn about how to link Julia code in R using XRJulia package, visit this Educative Answer.