gpt4 book ai didi

r - 在没有 `$` 的情况下访问网状 Python 对象

转载 作者:行者123 更新时间:2023-12-05 05:18:01 25 4
gpt4 key购买 nike

R 包 reticulate 有一个 custom $ operator它在等效的 Python 模块/对象中充当 . 运算符。由于 $ 的第二个参数 cannot be evaluated ,在这种情况下如何向它传递参数?

reticulate 自述文件中的示例用法是

library(reticulate)
os <- import("os")
os$chdir("tests")
os$getcwd()

我在下面的函数之后,其中 ... 将是带有零个或多个参数的 python 调用。

my_function <- function(python_object, ...)

python_object 需要属于类 python.builtin.objectpython.builtin.module 并且需要传递参数作为字符,因为这些函数在全局环境中不存在。

例如。

my_function(os, "chdir", "tests")
my_function(os, "getcwd")
my_function(r_to_py("my_string"), "lstrip", "my_")

我的想法是这样的

do.call("chdir", list("tests"), envir = os)

reticulate:::`$.python.builtin.object`(os, eval(parse(text="chdir('tests')")))

但是这些都不起作用。

最佳答案

实现起来比我想象的简单多了...

my_function <- function(python_module, attribute, ...) {
py_call(python_module[[attribute]], ...)
}

一般来说,$[[的简写。


更新

@jjallaire 指出...

py_call is a lower level function which doesn't currently get the benefit of type wrapping (but it certainly should).

要返回与 $ 相同的输出(即继承正确的类),请使用:

  • do.call(python_module[[attribute]], args = list(function_args))
  • python_module[[attribute]](function_args)

代替 py_call

参见 rstudio/reticulate#149 .

关于r - 在没有 `$` 的情况下访问网状 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48373739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com