Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Python function from R reticulate in Rmarkdown

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?

like image 215
Alexis Avatar asked Jun 10 '21 03:06

Alexis


Video Answer


1 Answers

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

like image 132
Waldi Avatar answered Oct 12 '22 20:10

Waldi