Skip to content

Instantly share code, notes, and snippets.

@JohnCoene
Last active March 11, 2019 23:51
Show Gist options
  • Select an option

  • Save JohnCoene/eb53ca0556601b2121cd3e29f315735a to your computer and use it in GitHub Desktop.

Select an option

Save JohnCoene/eb53ca0556601b2121cd3e29f315735a to your computer and use it in GitHub Desktop.
String & expression
library(shiny)
string <- "print('from string')"
installExprFunction({print("from expression")}, "expr")
ui <- fluidPage(
verbatimTextOutput("string"),
verbatimTextOutput("expression")
)
server <- function(input, output, session){
output$string <- renderPrint({eval(parse(text = string))})
output$expression <- renderPrint({expr()})
}
shinyApp(ui, server)
library(shiny)
expr <- quote(rnorm(1000))
plot_ui <- function(id){
ns <- NS(id)
plotOutput(ns("plot"))
}
plot <- function(input, output, session, expr){
output$plot <- renderPlot({hist(eval(expr))})
}
ui <- fluidPage(
plot_ui("mod")
)
server <- function(input, output, session){
callModule(plot, "mod", expr = expr)
}
shinyApp(ui, server)
library(shiny)
expr <- quote(rnorm(100))
myFunc <- function(expr){
ui <- fluidPage(
plotOutput("plot")
)
server <- function(input, output, session){
output$plot <- renderPlot({
hist(
eval(expr)
)
})
}
shinyApp(ui, server)
}
myFunc(expr)
@DivadNojnarg
Copy link

With the wrapper I could do:

library(shiny)
expr <- quote(
  output$plot <- renderPlot({
    hist(rnorm(input$obs))
  })
)
myFunc <- function(expr){
  ui <- fluidPage(
    sliderInput(
      "obs", 
      "Number of observations:",
      min = 0, 
      max = 1000, 
      value = 500
    ),
    plotOutput("plot")
  )
  server <- function(input, output, session){
    eval(expr)
  }
  shinyApp(ui, server)
}
myFunc(expr)

I have to see if modules are a cleaner way to do that and what is the impact on user-friendliness

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment