如何在Rmarkdown中从R网状调用Python函数
我有这个 Rmarkdown,带有一个 python 函数:
---
title: "An hybrid experiment"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(reticulate)
```
```{r}
selectInput("selector",label = "Selector",
choices = list("1" = 1, "2" = 2, "3" = 3),
selected = 1)
```
```{python}
def addTwo(number):
return number + 2
```
我尝试addTwo在响应式上下文中使用该函数,所以我尝试了这个:
```{r}
renderText({
the_number <- py$addTwo(input$selector)
paste0("The text is: ",the_number)
})
```
但我收到了这个错误:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Detailed traceback:
File "<string>", line 2, in addTwo
我一定是做错了什么,请你指导我解决这个问题吗?
回答
这reticulate部分很好,错误实际上来自shiny.
以下是关于 的一些重要细节input$selector:
- 它应该事先定义为
selectInput - 它需要转换为数字
as.numeric - 如果选择尚未完成,
req(input$selector)将避免错误renderText
这有效:
---
title: "An hybrid experiment"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(reticulate)
```
```{python}
def addTwo(number):
return number + 2
```
```{r}
selectInput("selector",label = "Selector",
choices = list("choose 1" = 1, "choose 2" = 2, "choose 3" = 3),
selected = 1)
renderText({
the_number <- py$addTwo(as.numeric(input$selector))
paste0("The text is: ",the_number)
})
```