简体   繁体   English

如何从R网格调用Python方法

[英]How to call Python method from R reticulate

reticulate lets you interface with Python from R. In Python, it is common to use (class) methods to interact with your variables. reticulate允许您从R与Python交互。在Python中,通常使用(类)方法与您的变量进行交互。 How do I access/execute the method of one Python variable in R when using reticulate? 使用网状时,如何在R中访问/执行一个Python变量的方法? For example, if I create the following Python dictionary: 例如,如果我创建以下Python字典:

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

that is accessible using reticulate, 可以使用网状,

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

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

How can I call one of the methods from the dictionary class, eg keys() from R? 如何从字典类中调用其中一个方法,例如来自R的keys()

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

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

I tried: 我试过了:

```{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'

but both tries failed. 但两次尝试失败了。

As pointed out in Type Conversions , Python's dict objects become named lists in R. So, to access the equivalent of "dictionary keys" in R you would use names : 正如类型转换中所指出的,Python的dict对象在R中成为命名列表。因此,要在R中访问等效的“字典键”,您将使用names

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

You may choose to convert the result back to a dict -like object using reticulate::dict() . 您可以选择使用reticulate::dict()将结果转换回类似dict的对象。 The resulting object would then function as you want: 然后,生成的对象将按您的意愿运行:

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

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

Applying a little bit of introspection on the original Python chunk: 在原始Python块上应用一些内省:

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

In another R chunk: 在另一个R块:

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

You will get (1) all the attributes available for the Python object, (2) the dict keys; 您将获得(1) Python对象可用的所有属性, (2) dict键; (3) dict item; (3) dict项目; and (4) the dict values: (4) dict值:

在此输入图像描述

Observe the conversion from an R to Python object with r_to_py() . 使用r_to_py()观察从R到Python对象的转换。

If you want to dig deeper, you can also do this: 如果你想深入挖掘,你也可以这样做:

```{r}
library(reticulate)
builtins    <- import_builtins()

builtins$dict$keys(py$fruits)     # keys
builtins$dict$items(py$fruits)    # items
builtins$dict$values(py$fruits)   # values

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM