從 Python 與 R 匯入函式

Julia 中級

Anthony Markham

Quantitative Developer

套件總覽

  • 你可能想在 Julia 程式裡使用 Python 或 R 的套件。
  • 理由很多:

    • 對某套件較熟悉
    • 只有 Python 或 R 才有的特殊套件
    • 與其他程式碼維持一致
  • 兩個 Julia 套件可支援此功能——PythonCallRCall

using Pkg
Pkg.add("PythonCall")
Pkg.add("RCall")
  • 反向也可行——也能在 Python 與 R 中使用 Julia 程式碼。
Julia 中級

匯入 Python 套件

  • 使用 PythonCall 把 Python 的函式整合進 Julia 程式碼。
  • 任何 Python 套件都能用,只要它已安裝在 Python 中。
using PythonCall
  • 從 Python 載入套件,用 pyimport
pytime = pyimport("time")
  • PythonCall 中還有許多進階功能,本課不會涵蓋。
Julia 中級

呼叫 Python 函式

  • 我們可以呼叫 base time 套件中的任一函式。
using PythonCall
pytime = pyimport("time")
println(pytime.ctime())
Sun Jan 22 12:16:28 2023
  • 我們也能組合多個函式(含 Python 格式化)。
println(pytime.strftime("%m-%Y", pytime.localtime()))
01-2023
Julia 中級

匯入 R 函式庫

  • 使用 RCall 把 R 的函式整合進 Julia 程式碼。
  • 安裝 RCall 前需要先有 R。
  • 任何 R 套件都能用,只要也已安裝在 R 中。
using RCall
  • 在 R 載入套件,用 @rimport
@rimport base
@rimport ggplot2
  • RCall 中還有許多進階功能,本課不會涵蓋。
Julia 中級

呼叫 R 函式

  • 這裡我們會呼叫 base R 環境裡的函式。
  • 匯入套件時可設定別名。
using RCall
@rimport base as r_base
r_base.sum([1, 2, 3, 4, 5])
RObject{IntSxp}
[1] 15
Julia 中級

R 的 sum 輸出

  • 我們可以快速比較 Julia 與 R 的輸出。
RObject{IntSxp}
[1] 15

R 主控台輸出

Julia 中級

更多 R 函式呼叫

  • 接著試試 base 套件中的 abbreviate 函式。
r_base.abbreviate(["Anthony", "Rachel", "Steve", "Julia"], 3)
RObject{StrSxp}
Anthony  Rachel   Steve   Julia
  "Ant"   "Rch"   "Stv"   "Jul"

Julia 中級

一起來練習吧!

Julia 中級

Preparing Video For Download...