Importing Functions from Python and R

Intermediate Julia

Anthony Markham

Quantitative Developer

Package overview

  • We might want to use packages from Python or R in your Julia programs.
  • There are many reasons why we might want to do this:

    • familiarity with a certain package
    • niche package only available for Python or R
    • consistency with other code
  • Two Julia packages give this functionality - PythonCall and RCall.

using Pkg
Pkg.add("PythonCall")
Pkg.add("RCall")
  • Note that the reverse is possible - we can also use Julia code in Python and R.
Intermediate Julia

Importing python packages

  • Use PythonCall to integrate Python functions into our Julia code.
  • Any Python package can be used, as long it is also installed in Python.
using PythonCall
  • To load a package from Python, use pyimport.
pytime = pyimport("time")
  • Many advanced functions exist in PythonCall that we will not cover in this course.
Intermediate Julia

Calling python functions

  • We can call any function from the base time package.
using PythonCall
pytime = pyimport("time")
println(pytime.ctime())
Sun Jan 22 12:16:28 2023
  • We can combine multiple functions including Python formatting.
println(pytime.strftime("%m-%Y", pytime.localtime()))
01-2023
Intermediate Julia

Importing R libraries

  • Use RCall to integrate R functions into our Julia code.
  • An R installation is required before installing the RCall package.
  • Any R package can be used, as long as that package is also installed in R.
using RCall
  • To load a package in R, use @rimport.
@rimport base
@rimport ggplot2
  • Many advanced functions exist in RCall that we will not cover in this course.
Intermediate Julia

Calling R functions

  • We will be calling functions from the base R environment in this example.
  • We can provide an alias when importing a package.
using RCall
@rimport base as r_base
r_base.sum([1, 2, 3, 4, 5])
RObject{IntSxp}
[1] 15
Intermediate Julia

R sum output

  • We can quickly compare the output from Julia to the output that R gives.
RObject{IntSxp}
[1] 15

R console output

Intermediate Julia

Calling further R functions

  • We will now try the abbreviate function, also in the base package.
r_base.abbreviate(["Anthony", "Rachel", "Steve", "Julia"], 3)
RObject{StrSxp}
Anthony  Rachel   Steve   Julia
  "Ant"   "Rch"   "Stv"   "Jul"

Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...