How do you import a Python library within an R package using rPython?
基本问题是这样的:假设我正在编写通过
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) } |
如果在不导入库
如何在R包中导入Python库? 您如何用
看来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建议的那样,您可以在包中添加
您还可以在导入模块之前测试该模块是否已经导入,但是(a)使您陷入一些回归问题,因为您需要导入
If you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this.
(尽管诚然,在该页面的其他地方有关于某些可能会导致性能损失的质疑 s>讨论)。
但也许您的关注点是风格上的,而不是性能方面的...