Apply/map R function formals into new function body from code as string

后端 未结 1 332
野趣味
野趣味 2021-01-19 21:20

I want to take a user\'s code and convert reactive() calls into functions like this.

a <- reactive({
  i         


        
相关标签:
1条回答
  • 2021-01-19 21:46

    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.

    0 讨论(0)
提交回复
热议问题