从 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 函数

  • 我们可以调用 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 函数

  • 此示例将调用 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 中级

Vamos praticar!

Julia 中级

Preparing Video For Download...