I have a functioning shiny here, which is using "shinymeta" to extract the R-code from the shiny-script, so the user can generate the same output being generated in the shiny, even outside the shiny.
However, when you click on the "show code" button, before generating a plot, or after clicking on the reset button to delete the plot, and then clicking on the "show code" button the app will crash. so My question is, how can I make the app, "stupid proof" so if the user, clicks on the "show code" button, and there is no code to show the app won't crash?
library(shiny)
library(plotly)
library(dplyr)
library(shinymeta)
library(shinyjs)
dataset <- mtcars
ui <- shinyUI(fluidPage(
useShinyjs(),
headerPanel("Mtcars"),
sidebarPanel(sliderInput('sampleSize', 'Sample Size', min=10, max=nrow(dataset),
value=min(10, nrow(dataset)), step=5, round=0),
selectInput('x', 'X', names(dataset)),
selectInput('y', 'Y', names(dataset), names(dataset)[[2]]),
selectInput('color', 'Color', c('None', names(dataset))),
checkboxInput('smooth', 'Smooth'),
selectInput('facet_row', 'Facet Row', c(None='.', names(dataset))),
selectInput('facet_col', 'Facet Column', c(None='.', names(dataset))),
hr(),
checkboxInput("plotly1", "Interactive plot!",value = FALSE, width=140),
uiOutput("graghbutton"),
actionButton("reset", "Reset")
),
mainPanel(
outputCodeButton(plotOutput('plot')),
hr(),
hr(),
conditionalPanel("input.plotly1 === true", outputCodeButton(plotlyOutput("plot2"))),
verbatimTextOutput("code")
)
))
server<- function(input, output, session) {
dataset <- metaReactive( { mtcars[sample(nrow(mtcars), ..(input$sampleSize)),] })
output$graghbutton <- renderUI({
actionButton("plotxxx", "Plot!")
})
gragh <- metaReactive2({
req(input$plotxxx)
p <- isolate(metaExpr({
ggplot(..(dataset()), aes_string(..(input$x), ..(input$y))) + geom_point() }))
if (input$color != 'None')
p <- isolate(metaExpr({
..(p) + aes_string(color=..(input$color))
}))
facets <- isolate(metaExpr({
paste(..(input$facet_row), '~', ..(input$facet_col))
}))
if (facets != '. ~ .')
p <- isolate(metaExpr({
..(p) + facet_grid(..(facets))
}))
if (input$smooth)
p <- isolate(metaExpr({
..(p) + geom_smooth()
}))
p
})
observeEvent(input$plotxxx, {
req(input$plotxxx)
output$plot <- metaRender2(renderPlot, {
isolate(metaExpr({
..(gragh())
})
)
})
})
output$plot2 <- metaRender(renderPlotly, {
ggplotly(..(gragh()))
})
observeEvent(input$plot_output_code, {
code <- expandChain(quote(library(ggplot2)), output$plot())
displayCodeModal(code)
})
observeEvent(input$plot2_output_code, {
code <- expandChain(quote(library(ggplot2)), output$plot2())
displayCodeModal(code)
})
observeEvent(input$plotxxx, {
output$code <- renderPrint({
req(input$plotxxx)
isolate(expandChain(output$plot(),
output$plot2()
))
})
})
observeEvent(input$reset, {
output$plot <- renderPlot({
})
output$code <- renderPrint({
})
})
}
shinyApp(ui, server)