如何使用rPython在R包中导入Python库?

How do you import a Python library within an R package using rPython?

基本问题是这样的:假设我正在编写通过rPython调用python的R函数,并且我想将其集成到包中。 这很简单-R函数绕在Python上是无关紧要的,您可以照常进行。 例如

1
2
3
4
5
6
7
8
9
# trivial example
# library(rPython)
add <- function(x, y) {
  python.assign("x", x)
  python.assign("y", y)
  python.exec("result = x+y")
  result <- python.get("result")
  return(result)
}

但是,如果带有R函数的python代码要求用户首先导入Python库,该怎么办? 例如

1
2
3
4
5
6
7
8
9
10
11
12
# python code, not R
import numpy as np
print(np.sin(np.deg2rad(90)))

# R function that call Python via rPython
# *this function will not run without first executing `import numpy as np`
print_sin <- function(degree){
   python.assign("degree", degree)
   python.exec('result = np.sin(np.deg2rad(degree))')
   result <- python.get('result')
   return(result)
}

如果在不导入库numpy的情况下运行此命令,则会出现错误。

如何在R包中导入Python库? 您如何用roxygen2进行评论?

看来R标准是这样的:

1
2
3
4
5
6
7
8
9
# R function that call Python via rPython
# *this function will not run without first executing `import numpy as np`
print_sin <- function(degree){
   python.assign("degree", degree)
   python.exec('import numpy as np')
   python.exec('result = np.sin(np.deg2rad(degree))')
   result <- python.get('result')
   return(result)
}

每次运行R函数时,都将导入整个Python库。


正如@Spacedman和@DirkEddelbuettel建议的那样,您可以在包中添加.onLoad / .onAttach函数,该函数调用python.exec导入通常由包用户始终需要的模块。

您还可以在导入模块之前测试该模块是否已经导入,但是(a)使您陷入一些回归问题,因为您需要导入sys才能执行测试,(b)答案是 这个问题表明,至少就性能而言,这无关紧要,例如

If you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this.

(尽管诚然,在该页面的其他地方有关于某些可能会导致性能损失的质疑讨论)。
但也许您的关注点是风格上的,而不是性能方面的...