How to call Python function from R reticulate in Rmarkdown
Asked Answered
M

1

7

I have this Rmarkdown, with a python function:

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

And I try to use the function addTwo in a reactive context, so I tried this:

    ```{r}
    renderText({
      the_number <- py$addTwo(input$selector)
      paste0("The text is: ",the_number)
    })
    ```

But I got this error:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Detailed traceback:
  File "<string>", line 2, in addTwo

I must be doing something wrong, please could you guide me to solve this problem?

Mat answered 10/6, 2021 at 3:27 Comment(0)
H
5

The reticulate part is fine, and the error actually comes from shiny.

Here are a few important details regarding input$selector:

  • it should be defined beforehand with selectInput
  • it needs to be converted to numeric with as.numeric
  • in case selection is not yet done, req(input$selector) will avoid an error in renderText

This works:

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

enter image description here

Homophony answered 12/6, 2021 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.