Created
December 1, 2020 05:22
-
-
Save jimbrig/01836ec44af0c0885fbec10e0a879391 to your computer and use it in GitHub Desktop.
[Defuse Shiny Reactives] Useful R Code Displaying How to "Defuse" Reactives into Static Values #dev #shiny #pinned
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| code <- | |
| "library(shiny) | |
| library(dplyr) | |
| library(ggplot2) | |
| input <- list(cty = 15) | |
| df = shiny::reactive({ | |
| x <- input$cty | |
| mpg %>% filter(cty < x) | |
| }) | |
| this_is_crazy <- shiny::reactive | |
| n_obs <- reactive(nrow(df())) | |
| df_head <- this_is_crazy(head(df()))" | |
| # or if code is in a script use code <- file(<path>) | |
| is_assigned_reactive <- function(expr) { | |
| # discard obvious | |
| if ( | |
| rlang::is_symbol(expr) || | |
| !(expr[[1]] == "<-" || expr[[1]] == "=") || | |
| length(expr) != 3 | |
| ) { | |
| return(FALSE) | |
| } | |
| fn_expr <- expr[[3]][[1]] | |
| # Check that it's actually `shiny::reactive` being called | |
| identical(rlang::eval_bare(fn_expr), shiny::reactive) | |
| } | |
| replace_reactive_expr <- function(expr) { | |
| if (length(expr) > 1) { | |
| # recurse all the way into the parsed code tree | |
| lapply(expr, replace_reactive_expr) | |
| } | |
| # on the way back up, catch any assigned reactives | |
| if (is_assigned_reactive(expr)) { | |
| # and replace the reactive with a function | |
| expr[[3]] <- rlang::new_function(NULL, expr[[3]][[2]]) | |
| } | |
| expr | |
| } | |
| eval_with_defused_reactive <- function(code, envir = globalenv()) { | |
| # parse the code, then evaluate each expression after replacing reactives | |
| exprs <- rlang::parse_exprs(code) | |
| for (expr in exprs) { | |
| eval(replace_reactive_expr(expr), envir = envir) | |
| } | |
| } | |
| eval_with_defused_reactive(code) | |
| df() | |
| n_obs() | |
| df_head() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(shiny) | |
| library(dplyr) | |
| library(ggplot2) | |
| input <- list(cty = 15) | |
| df <- shiny::reactive({ | |
| x <- input$cty | |
| mpg %>% filter(cty < x) | |
| }) | |
| this_is_crazy <- shiny::reactive | |
| n_obs <- reactive(nrow(df())) | |
| df_head <- this_is_crazy(head(df())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment