Bring the power of Julia into R through XRJulia package (2)

Introduction to Julia and XRJulia package by example

Julia is a high-performance language, it is easy to learn if you are already familiar with R. You can find introduction and many useful links for Julia from https://julialang.org/. XRJulia is a package for R by John M. Chambers. It enables us to access to all the functionality provided by Julia in R. You can get it from CRAN or the latest version from https://github.com/johnmchambers/XRJulia. The purpose of this article is to give a brief introduction to Julia and XRJulia with some small examples.
After installing XRJulia package, let us type the following code into R:
library("XRJulia")
ev <- RJulia()
ev$Eval("1+1") ## 2
ev$Command("a = 1+1")
ev$Eval("a") ## 2
The first line is to load the XRJulia library, and the second line is to start a Julia session with the name ev (which is the abbreviation for evaluator). And then you can evaluate some expression using ev$Eval or execute some commands through ev$Command with the evaluator you just created. Note that you can create multiple Julia session and have multiple evaluators through RJulia, but need to set .makeNew = TRUE. For example, you can do the following:
ev1 <- RJulia()
ev1$Eval("a") ## 2
## So you can see ev1 and ev are actually 
## for the same Julia session
identical(ev, ev1) ## TRUE
## So you can see ev1 and ev are actually the same evaluator
ev2 <- RJulia(.makeNew = TRUE)
ev2$Eval("a") ## Julia error: UndefVarError: a not defined
## So ev2 and ev are different evaluators connected to 
## different Julia session.
And we can see some more complex examples besides the basic operations. For example, we know that package like CVX for MATLAB is lack in R. Fortunately, similar functionalities are provided by Convex.jl in Julia. So after installing Convex.jl (https://github.com/JuliaOpt/Convex.jl) into Julia. We can use Convex.jl in R to solve a simple linear programming problem:
where , , and .
library("XRJulia")
ev <- RJulia()
ev$Command("using Convex")
ev$Command("x = Variable(4); c = [1; 2; 3; 4]; A = eye(4); b = [10; 10; 10; 10]")
ev$Command("p = minimize(dot(c, x))")
ev$Command("p.constraints += A * x <= b; p.constraints += [x >= 1; x <= 10; x[2] <= 5; x[1] + x[4] - x[2] <= 10]")
ev$Command("solve!(p)")
ev$Eval("p.optval") ## which returns the optimal value
ev$Eval("x.value", .get = TRUE) ## which returns the solution
Although this is a simple problem, we can see how easy linear programming problem (or second order and semidefinite programming problem) can be formulated and be solved by using Convex.jl through XRJulia in R.
In the next post of this series of blogs, we will see how we can use more advanced facilities provided by XRJulia to write a wrapper for Convex.jl in R.

Comments

Popular posts from this blog

Improve R's Performance using JuliaCall

Convex Optimization in R by convexjlr