【问题标题】:How to call Python method from R reticulate如何从 R reticulate 调用 Python 方法
【发布时间】:2018-12-09 01:28:10
【问题描述】:

reticulate 允许您从 R 与 Python 交互。在 Python 中,通常使用(类)方法与变量进行交互。使用 reticulate 时如何访问/执行 R 中一个 Python 变量的方法?例如,如果我创建以下 Python 字典:

```{python}
fruits = {
    "apple": 53,
    "banana": None,
    "melon": 7,
}
```

可以使用 reticulate 访问,

```{r}
py$fruits
```

## $apple
## [1] 53
## 
## $banana
## NULL
## 
## $melon
## [1] 7

如何调用字典类中的一种方法,例如keys() 来自 R?

```{python}
print(fruits.keys())
```

## dict_keys(['apple', 'banana', 'melon'])

我试过了:

```{r error=TRUE}
py$fruits$keys()
```

## Error in eval(expr, envir, enclos): attempt to apply non-function

```{r error=TRUE}
py$fruits.keys()
```

## Error in py_get_attr_impl(x, name, silent): AttributeError: module '__main__' has no attribute 'fruits.keys'

但两次尝试都失败了。

【问题讨论】:

标签: python r reticulate


【解决方案1】:

正如Type Conversions 中所指出的,Python 的 dict 对象在 R 中成为命名列表。因此,要访问 R 中的“字典键”等价物,您可以使用 names

```{r}
names(py$fruits)
```
## [1] "melon"  "apple"  "banana"

您可以选择使用reticulate::dict() 将结果转换回类似dict 的对象。然后,生成的对象将按您的意愿运行:

```{r}
reticulate::dict( py$fruits )
```
## {'melon': 7, 'apple': 53, 'banana': None}

```{r}
reticulate::dict( py$fruits )$keys()
```
## ['melon', 'apple', 'banana']

【讨论】:

    【解决方案2】:

    对原始 Python 块应用一点内省:

    ```{python}
    fruits = {
    "apple": 53,
    "banana": None,
    "melon": 7,
    }
    ```
    

    在另一个 R 块中:

    ```{r}
    py_fruits <- r_to_py(py$fruits)
    py_list_attributes(py_fruits)
    py_fruits$keys()
    py_fruits$items()
    ```
    

    您将获得 (1) 可用于 Python 对象的所有属性,(2) dict 键; (3) 字典项;和 (4) dict 值:

    使用r_to_py() 观察从 R 到 Python 对象的转换。

    如果你想深入挖掘,你也可以这样做:

    ```{r}
    library(reticulate)
    builtins    <- import_builtins()
    
    builtins$dict$keys(py$fruits)     # keys
    builtins$dict$items(py$fruits)    # items
    builtins$dict$values(py$fruits)   # values
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2022-06-28
      • 1970-01-01
      相关资源
      最近更新 更多