【问题标题】:How to call Python function from R reticulate in Rmarkdown如何在 Rmarkdown 中从 R reticulate 调用 Python 函数
【发布时间】:2021-08-27 01:20:00
【问题描述】:

我有这个 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

我一定是做错了什么,请你指导我解决这个问题吗?

【问题讨论】:

    标签: r shiny r-markdown reticulate


    【解决方案1】:

    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)
    })
    ```
    

    【讨论】:

    • 您好@Waldi,感谢您的回答,当我看到您的评论时,我意识到我错过了输入选择器。我已将它添加到问题中,我怀疑因为它是一个列表,所以我不能添加 2,因为它是一个列表。请问,你知道我该如何解决吗?因为我的主要目的是管理一个参数(比如说一个名称、一个数字等),将它传递给一个 python 函数,然后返回一个反应值或绘图。谢谢
    • @Alexis,它也适用于列表,请参阅我的编辑。 as.numeric 仍然是必要的。
    • 非常感谢@Waldi,我测试了解决方案并且工作正常。
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2018-09-05
    • 2022-06-28
    • 2019-07-08
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多