如何在 Rmarkdown 中从 R 网状结构调用 Python 函数
How to call Python function from R reticulate in Rmarkdown
我有这个 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)
})
```
我有这个 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)
})
```