[SOLVED] Julia equivalent of R's `require()` function


I am starting to write some Julia functions that rely on other packages for their computations. For example, in R, I will write the following if my function depends on the dplyr package.

foo <- function(x){
  require(dplyr) # the body part will use the package `dplyr`

What’s the equivalent in Julia and, are they any best practices/suggestions when it comes to that? By now I am using using Pkg inside the body of the functions, but I am not sure about it. Thank you.


You are probably looking for using. You can either using an entire package

using LinearAlgebra

or you can specify a list of just the specific things you want to use

using StasBase: fit, Histogram

There is also import but that is mostly used either
(A) when you want to include a file, rather than a package or

(B) when you want to extend a function from another package (including Base, if you want!) for, e.g., your custom types.

struct Point{T}

import Base.+
function +(a::Point, b::Point)
    return Point(a.x + b.x, a.y + b.y)
julia> Point(3,5) + Point(5,7)
Point{Int64}(8, 12)

But unless you want to do that, you probably just need using.

The major difference is that you would not normally put your using statement within a function (rather put it at top level instead). Depending on code from another package only within a single function would arguably be a bit un-Julian.

Answered By – cbk

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.