I want to take a user\'s code and convert reactive()
calls into functions like this.
a <- reactive({
i
This is inspired by data.table's way of replacing its .()
alias.
code <-
"library(shiny)
input <- list(cty = 15)
df <- reactive({
x <- input$cty
mpg %>% filter(cty < x)
})
n_obs <- reactive(head(df()))"
all_expr <- parse(text = code)
f_recurse_look = function(e) {
if (is.call(e)) {
if (e[[1L]] == "reactive")
e = as.function(as.list(e)[-1L])
else
for (i in seq_along(e)[-1L]) if (!is.null(e[[i]])) e[[i]] = f_recurse_look(e[[i]])
}
e
}
lapply(all_expr, f_recurse_look)
#> [[1]]
#> library(shiny)
#>
#> [[2]]
#> input <- list(cty = 15)
#>
#> [[3]]
#> df <- function ()
#> {
#> x <- input$cty
#> mpg %>% filter(cty < x)
#> }
#>
#> [[4]]
#> n_obs <- function ()
#> head(df())
This approach will recursively look through the expression calls until it finds reactive
. Note, this means that if reactive
is in multiple calls in a single expression, this solution would need modified.