While I mainly use
Julia when conducting analysis with the LRMoE model, the vast majority of actuaries still use
R for statistical analysis. Hence, it could be useful to improve the current
R version of the package. In this process, cross checking between
R is a common task.
RCall.jl package allows for good interface between these two languages, making my life easier. The official documentation provides a comprehensive guide to the package. Here, I will just note down important steps and functionalities which I find particularly useful.
If no setup is done for the
RCall.jl package, it automatically emulates a brand-new
R session. This is undesirable since I may want to use existing
R packages on my computer. To use my version of
R, I need to run the following.
# Set "R_HOME" to your R directory, i.e. the path returned by `R> R.home()` ENV["R_HOME"] = "C:\\Program Files\\R\\R-4.0.2" # R.home() for my computer Pkg.build("RCall")
A few things to notice:
These two lines should only be run ONCE in a single Julia session. Otherwise there would be some error message.
It suffices to run them ONCE in a single project. Afterwards, the
RCall.jl is always using the same
R installation unless
ENV["R_HOME"] is changed and the
RCall.jl package is built again.
Julia REPL, we can access
R by pressing
julia> will become
R> and we can do the usual
R stuff there. When we are done with
R, just press Backspace to return to
Julia. This is analogous to accessing the
Pkg package manager by pressing
Alternatively, we can write longer
R code chunks like the following, and then run the whole code chunk together.
R""" x = 3 print(paste("My x is set to be ", x, ".", sep = "")) """
It is certainly possible to
R scripts, allowing for even more calculations / data manipulation / ... in native
The most important interaction between
Julia is probably transferring data, e.g. passing a variable in
R and vice versa. This is easily done by two macros:
For example, the following code will pass
x_R = 3 from
Julia. The same task can also be done by the
R""" x_R = 3 """ x_julia = @rget x_R
Similarly, the following code will pass
y_julia = 5 from
R. Note that the same variable name is also passed into
R (which is different from the above where you can set a different variable name).
y_julia = 5 @rput y_julia R""" y_julia # Should return 5 """
For transferring basic data types such as numbers and strings (single variable, vectors and matrices), the examples above are sufficient. For more complex data types, e.g. logicals, or even customized data types, the procedure may be more involved, which I have not yet tried out.
In this post, I have covered the basic interface with
Julia using the
RCall.jl package. Of course, it is also possible to go the other way around, interacting with
R package I found is
JuliaCall, which I will probably write about when I use it. A good comprehensive post that covers this topic is given here.