passing reactive R object to python code in Rmd?

I am wondering if there is a way to pass a reactive value, for example the result of shiny::numericInput() , as a parameter to python code in a python chunk. sample code below:

---
title: "rective R value in python code reprex"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(reticulate)
library(tidyverse)
library(shiny)
```

## non-reactive input

```{r}
my_number <- 4
```

(note: the chunk below is a  python chunk defined using `{python}` in the chunk header)

```{python}
def my_function(x):
  return 5 * x

result = my_function(int(r.my_number))
```

works when kitting!
```{r}
py$result
```

----------

## trying with reactive input

```{r}
shiny::numericInput(inputId = "number_select", label = "Number", value = 4, min = 1, step = 1)

my_number <- 
  reactive(input$number_select)
```

(note: the chunk below is a  python chunk defined using `{python}` in the chunk header)

```{python}
def my_function(x):
  return 5 * x

# the following line results in error: 
#   Error in py_call_impl(callable, dots$args, dots$keywords) : 
#   RuntimeError: Evaluation error: Operation not allowed without an active reactive context.
# * You tried to do something that can only be done from inside a reactive consumer..

result_reactive = my_function(int(r.my_number()))

# removing the parens results in error:
  # Quitting from lines 43-54 (reprex_example.Rmd) 
  # Error in py_call_impl(callable, dots$args, dots$keywords) : 
  #   TypeError: int() argument must be a string, a bytes-like object or a number, not 'function'
  
result_reactive = my_function(int(r.my_number))
```

never makes it to this step whe knitting :(
```{r}
py$result_reactive
```

I am not quite sure this is supported in this way . Shiny and reactive values are from R and using a python chunk will pass the python code to python runtime but the r.my_number() will not be used in the right context.

What about loading your python function in R and then use python from R ?

I think you would do that in a shinyApps outside of a R Markdown document.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.