Skip to content

Instantly share code, notes, and snippets.

@wilsoncai1992
Forked from jcheng5/withConsoleRedirect.R
Created June 29, 2016 17:10
Show Gist options
  • Save wilsoncai1992/acb2b7a84657cb8aad383ce302db4ed2 to your computer and use it in GitHub Desktop.
Save wilsoncai1992/acb2b7a84657cb8aad383ce302db4ed2 to your computer and use it in GitHub Desktop.
Someone at #useR2016 asked me if you can have Shiny execute code in observers/reactives but send the console output to the browser.
library(shiny)
withConsoleRedirect <- function(containerId, expr) {
# Change type="output" to type="message" to catch stderr
# (messages, warnings, and errors) instead of stdout.
txt <- capture.output(results <- expr, type = "output")
if (length(txt) > 0) {
insertUI(paste0("#", containerId), where = "beforeEnd",
ui = paste0(txt, "\n", collapse = "")
)
}
results
}
# Example usage
ui <- fluidPage(
pre(id = "console")
)
server <- function(input, output, session) {
observe({
invalidateLater(1000)
withConsoleRedirect("console", {
str(cars)
})
})
}
shinyApp(ui, server)
@wilsoncai1992
Copy link
Author

Thanks Joe!

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