Shiny debugging and reprex guide

Shiny issues can be challenging to resolve relative to other problems with your code or statistical methods. Shiny apps are often large, complex projects with interacting files.

When seeking help from others it is considered polite to:

  • First, do your best to work through RStudio's debugging tools to diagnose your issue on your own. Often those shiny logs and tracebacks are useful to others trying to help out.
  • Second, strive to minimize the effort required to replicate your issue. You can do this with a reproducible example ("reprex").

Shiny Debugging

Errors in Shiny code can be difficult to track down. If you don't know where your problem is coming from, you can track it down with some of the techniques here:

Add browser() in strategic places. When R executes browser(), it will stop the application and let you run commands at the console to poke around and inspect values. For example, here is a browser() call inserted at the top of some plotting code:

output$plot <- renderPlot({
  browser()
  n <- input$n * 2
  plot(head(cars, n))
})

When R reaches the browser(), it will pause execution of the application and show you this at the console:

Called from: top level 
Browse[1]> 

You can inspect variables (like input$n), modify variables, and step through the code. When R is at the debug prompt, it supports the following special commands:

  • Type n then Enter: this runs the next line of code.
  • Type c then Enter: this continues normal execution and exits the debugger prompt.
  • Type s then Enter: this steps into the a function.

For more information about debugging R in general, see this chapter in Hadley Wickham's Advanced R book.

Also see the article on Debugging Shiny applications if you want to learn more about debugging Shiny applications in particular.

Creating Shiny reprexes

If you need to ask for help, you are much more likely to get help if you have a minimal reproducible example ("reprex") which other people can copy and paste to see the same problem. When the code is minimal, it makes it easy for others to see where the problem is. And if the problem can be reproduced by copying and pasting, it makes it much easier for others to debug the problem.

Here is an example of a reprex. If you copy and paste the code in an R console, the application will show an error: non-numeric argument to binary operator.

shinyApp(
  ui = fluidPage(
    selectInput("n", "N", 1:10),
    plotOutput("plot")
  ),
  server = function(input, output, session) {
    output$plot <- renderPlot({
      n <- input$n * 2
      plot(head(cars, n))
    })
  }
)

Because anyone can reproduce the problem by just copying and pasting the code, they can easily explore your code and test possible solutions.

How do I create a reprex from my application?

If you don't know what part of your code is triggering the problem, a good way to find it is to remove sections of code from your application, piece by piece, until the problem goes away. If removing a particular piece of code makes the problem stop, it's likely that that code is related to the problem. Once you've isolated the code that triggers the problem, you can go on to the next step.

To create a minimal example, you can go one of two ways: you can either keep removing code from your application until all the extraneous parts are gone, or you can construct a new Shiny application and copy the problem code into the new application. It's generally easier for others to understand the problem when you construct a new example, although either way is much better than not having a reproducible example at all.

If you want to construct a minimal example from scratch, you can start with this template of very basic application, which you can always find by running ?shinyApp (that shows the documentation for the function).

  shinyApp(
    ui = fluidPage(
      numericInput("n", "n", 1),
      plotOutput("plot")
    ),
    server = function(input, output, session) {
      output$plot <- renderPlot( plot(head(cars, input$n)) )
    }
  )

Start with the template and modify it by adding code that reproduces your problem. In many cases, the act of creating a reproducible example will reveal to you the cause of the problem, before you even ask for help.

Dealing with data

If your reproducible example uses a data set that is stored on your computer, it will be difficult for others to reproduce the problem, because they won't be able to just copy and paste your code; they'll have to download the data, run R in the correct directory, and so on.

You can make it easier for others by providing a data set in a way that can be copied and pasted. This can be either your original data set, or a simplified version of it that still causes the issue. For example, if you have a data frame with 1,000 rows, you might try to take the first 20 rows and see if that will still cause the problem. In general it is best to provide a simplified version of the data set, so that it is easy for others to understand it.

Option 1: Provide regular R code that generates a data set. For example:

mydata <- data.frame(x = 1:5, y = c("a", "b", "c", "d", "e"))

Option 2: Use dput(). If you have an object x, calling dput(x) will print out code that will generate an object just like x. For example, if you use dput(mydata), it will print the following:

> dput(mydata)
structure(list(x = 1:5, y = structure(1:5, .Label = c("a", "b", 
"c", "d", "e"), class = "factor")), class = "data.frame", row.names = c(NA, 
-5L))

If you run the structure(list(....)) code, it will return a data frame exactly like mydata. Once you have that code, you can put this in your application to generate mydata:

mydata <- structure(list(x = 1:5, y = structure(1:5, .Label = c("a", "b", 
"c", "d", "e"), class = "factor")), class = "data.frame", row.names = c(NA, 
-5L))

If dput() on your original data generates too much code, try taking a subset of your data and see if it will reproduce the problem.

Please bear in mind that dput() is not perfect, and cannot faithfully reproduce every kind of R object. It will, however, work for most objects, like data frames and vectors.

Option 3: If your data set can't be put in your code in a way that can be copied and pasted, you might have to just upload it so that others can download it. It is best to avoid this if possible.

Personal and Private Information

Users should not share personal or protected information in topic threads or reprex data.
What if you need to share contact info or an ip, or discuss data for a reprex related to a protected dataset? What if you see a violation of this policy? Check out Personally Identifiable & Protected Information Guide guide and our Privacy Policy

11 Likes
Add more content in descriptionBlock while using ShinyDashboard
Rshiny throws error after publish the app
Reactive values not working
<!DOCTYPE html> in rendered Rmd document
How to browse audio files from local system using R Shiny?
Need help getting my Shiny App to deploy
DT tables not updating while other tables are
Shiny app disconnects only on server--logs show no errors
Shiny Error - Seurat Integration | Reactive Value error
When select elements with control in selectInput new chrome page is opening, how could I avoid it?
Load data from excel file
Click on map marker to show ggplot line chart
Automatic scale with ggplot
Validate, need doesn't show the message in renderplotly
Clearing the Search Data From 1st Iteration - R Shiny Dash Board
A question about shiny minichart
Prevent showing output until the action button is clicked
numericInput - hint implies only integer values valid
Disconnected from the server - shinyapps.io & googlesheet
renderPlot loops continuously with req()
shiny upload file example: "Error: an error had occured. Check your logs or contact the app author for clarification"
Lazy loading Plots in Shiny based on Tab selected
Use Shiny to create a checkbox list?
update action button values
Plot a data with two columns in shiny app based on selection
Help with a strange Error messsage
Refreshing page when you change radio buttons
Help needed for Shiny app with the code
Show different results on datatable in Shiny
shinyapp of "retirement simulation" does not work for me
What's the best way to plot graph using AcctionButton?
how can I summarize survey answers from a data table in R shiny?
How change default selected value for "radioButtons" UI element?
Local data preventing application from loading on shinyapps.io
Quick question re: data in reactive function in shiny
How to put "Input values" on the Box Title
Cannot run Shiny App after installing Ubuntu
Columns must be 1d atomic vectors or lists
Best way to debug a shiny app
Shiny App disconect from server
Unable to reset inputs using shinyjs
Shiny app shows "disconnected from server" on Shiny.io even right after starting
UTF8 saving problem
Playing Audio Files Made in the App with the Audio Package in ShinyDashboard
namespace ‘htmlwidgets’ 0.9 is being loaded, but >= 1.3 is required
How update data cache for Shiny server?
App is working fine locally but when published on shinyapps.io receiving blank screen!
Bypass "Reading objects from shinyoutput object not allowed"
avoid flexdashboard pages in same project share objects
Edit datas with a Shiny App
refresh the plot after adjusting radio button and slider
Cannot download PDF reportin shinyapps.io
Using dateRangeInput with BETWEEN logic in SQL
Bioconductor - karyoploteR | issues making an R-shiny app with this package.
file.info does not work in r shiny?
file seems to reset
Latest data loaded in shiny apps getting lost
Deploying issue in shiny apps.io with mysql database
how to update shiny app deployed through shiny apps.io
Disconnected from server - Reload "What causes this error message on a deployed app?"
Warning: Error in : invalid assignment for reference class field ‘language’, should be from class “character” or a subclass (was class “NULL”)
Association Rules/Market Basket Brainstorming.
Error : unable to start png() device - Rshiny
Error from shinyapps.io : An error has occurred Unable to connect to worker after 60.00 seconds; startup took too long.
RStudio - set column as selectInput values
else If statement not working on shinyapps.io
Aesthetics must be either length 1 or the same as the data (8): x, y, fill
GLUE package error in input values
Dataframe not loading on RenderDataTable
Shiny functions having compilation issues
Transaction wait time - Time difference between rows in the same column - Shiny R
Shiny Graphic disappears when i switch from a tabPanel to another
Error in : Clipboard on X11 requires that the DISPLAY envvar be configured
Unable to open R Shiny (flexdashboard widget) in Google Chrome
Get an infoBox to update automatically from selectInput
When ever I change the choices in the R Shiny error occurs: ERROR: value 'NA' not found in choices Warning: attributes are not identical across measure variables; they will be dropped""
Getting URL parameters in a shiny dashboard app
R Shiny, checkBox, tabPanel
Could not find function reactiveEval()
Translating HTML coordinates to plot coordinates
Python in shiny app
getting unused arguments (input = list(, TRUE, function (x) ) in R
Shifting moving axes/ making plot smaller
shinyjs: how to test if a menuItem is currently shown or hidden?
Object not found when I tried shiny i r markdown
Mobile current location in r shiny
how to pass multiple dataframes to different output in shiny in r
renderPrint in interactive shiny document does not work properly
Show all rows selected with either or both of the selectids
How to save the value of an output to use it in another output?
R shiny buttons
Shiny error on server
Not found when I refresh my shiny app
Interactive labels in ggplot
Error: package ‘xts’ required by ‘quantmod’ could not be found
Have a progressBox add more than one input and add together
Changing renderPlot colors from gpkg file
Navbar Pages data load and execution scheduling
how to update table variables depending on the data entry/input and submit buttom
For loop in inside render UI
R Shiny / Flex Dashboard is very slow post running it
R Shiny - Manipulating a `tagList` of Shiny inputs
Reference the dataframe that is drawn from the for loop
issues with infoBox in Shiny Dashboard
plotlyProxy on map in shiny
CheckboxGroupInput issues when accessed from webbrowser
warning: error in as.double: cannot coerce type 's4' to vector of type 'double'
shiny coupled event with R
shiny coupled event with R
DF not found to plot a graphic
R Shiny - downloadHandler
$ operator is invalid for atomic vectors
Combining different types of plots on the same shiny app
Rshiny- save the results and talk to server
Error: startup took too long
App not working on shinyapps.io - "could not find function '%>%'"
Using output of function in observeEvent as input to global.R in shiny app?
trying to upload csv data on shiny app
shiny app histogram - connected to ID the customer enters
Error in SelectInput
Freeze x-axis within chart Area R shiny
Shiny App Disconnected From Server When Selecting an Input and Popups Not Working
My Post Doesn't Have a Response - Advice on increasing the chances of getting help with my coding question
I could not get data from selectizeInput to esquisseUI
Question about Scoping for input objects in shiny application
SSL Read Error when making an API call from R Shinny App
ignore observeEvent during updateSelectInput
can we have loop in ui.R
Shiny Display issues
Shiny plot not showing
Error in map$get: key must be not be "" or NA
Radio buttons not working in esquisse package in r shiny Dashboard
How to use plotly for graphical representation
Action button and selectInput in R Shiny: Passing input of selectInput (multiple = TRUE) to a function only after final selection is made
Convert R script into Shiny App
Convert server file into HTML
Error deploying app to rsconnect
Error in `$<-.data.frame`(`*tmp*`, "config_url", value = "https://www.shinyapps.io/admin/#/application/") : replacement has 1 row, data has 0
how to convert factor to numeric in shiny
Reactive functionality has stopped working!
Creating ggplots bar diagram in Shiny
Data partition in shiny using caret package
Issue with timestamp on x axis -- ggplot/plotly
Help with Shiny app execution error
Shiny multi class classification
Shiny dashboard works well on MAC OSx and not on Windows 10
Big box beside 4 small boxes using shinydashboard
Error message : No stack trace available
app.R did not return a shiny.appobj object
Deployinging issue in shiny
Issuing POST from within a shiny app
How not to reload variables in shiny?
Whitespace in ggplot donut chart
Shinyapps can't find the excel file
Using a URL to Pipe Information into a shiny application
How to I attract help to my tricky Shiny and R Markdown problem? - Using paramterized Rmarkdowns and ShinyR apps/ Interactive markdown files
trying to get slot "className" from an object of a basic class ("function") with no slots
Shiny, leaflet: Link map click event with plotly highlight feature
error deploying shiny app with shinyapps.io
Rmd works fine in R but not in shiny
filtering action not occurring within eventReactive for dynamically-generated selectInput default choice
`curl` package not installed, falling back to using `url()`
"Warning: Error in : object of type 'closure' is not subsettable: error message
Shaky Shiny Server application when accessing the Drop-down menu
actionButton availability requirement
Shiny Error: Unable to establish connection with R session
Shiny Multi values text
To translate SelectInputs (Dropdown) using shiny.i18n package
R shiny front-end is stopping working help me
Does Shiny Server require apps to be split into ui.R and server.R?
assignment of an object of class “numeric” is not valid for @‘Dim’ in an object of class “dgTMatrix”; is(value, "integer") is not TRUE
Error in menu: menu() cannot be used non-interactively
render Image not outputting Shiny
Error when deploying new version
checkboxinput on DT / R Shiny
Disconnected from Server whenever two people use the app?
Shiny UI Elements Not Seen
'www' folder unavailable to the webserver when using 'Run Selected Line(s)' in RStudio
RShiny App Disconnected From Server
Stacked bar chart with ggplot2 and plotly groups with 1 observation the tooltip is missing.
Can someone please tell me what this error means in shiny?
"Can't subset columns that don't exist"
R Shiny: DataTables Warning: Invalid JSON response
My geom_curve function does not work
Shinyapp displays only on left-half of the screen
how to use input function even out of it's scope
data.frame in reactive , and after formattable : getting error : object of type 'closure' is not subsettable
R Shiny App: Filtering for conditional select Input
Warning: Error in tempVarsPromiseDomain: argument "name" is missing, with no default
Shiny App Leaflet map doesn't filter correctly by year
RStudio Community - Find Help - Guide
leaflet map not rendering with shiny input
Exporting and Importing Lists
Extracting the data from a radioButton
R shiny dashboard is not recognizing newly variables I have created in code
Shiny: "Application failed to start (exited with code 137)"
Error while running Shiny app
Strange Error Message...
How to make the app fill the window?
R Shiny for reading a csv file
Only create a server module /function without the UI part in R Shiny
How to write “function” or “if” with day, If my data does not exist every day. Shiny dashboard
How to remove white square of empty plot before variable loads
Highlight a bar with input in a ggplot / renderPlotly
Error: account not found for provided API key
Shinydashoard Sesession Error
Error in shiny while using predict
Shiny: how to use a dataframe as an input for an interactive graph
problem with if-else in shiny
Error in shiny while using predict
Shiny app not launching after R/Rstudio and pkgs upgrade
Beginner question table1 in Shiny
An error has occurred. ERROR: Check your logs or contact the app author for clarification.
Shiny application that only shows the screen and tables after clicking the button.
2 observer doesn't display at the same time
Error in func(fname, ...) : app.R did not return a shiny.appobj object.
Moving objects in shiny UI
Action Button to Add Data to Dataframe -- Warning: Error in data.frame: arguments imply differing number of rows: 0, 1
Shiny App does not find object after deployment.
Mapview no longer renders in Shiny
Shiny App Running Locally but just says Please Wait Eternally when published on free shiny server
shiny output messing up
renderDataTable ID
shiny app shows error code 1 but works fine in my local page
Shiny app works locally, but failed to start when published to shinyapps.io, logs look normal without errors
Having error in uploading file : error 'arg' should be one of “link”, “response”, “terms”
New to shiny- need help autoplotting stocks
Selected file to graph
Cut/paste graphics as high quality
Error - Application failed to start
Shiny GGPlot Error: Arguments must have the same length
observe not registering reactive value
Unable to update value in updateDateInput
When add new tabPanel in Shiny this appear in all tabs.
Creating a drop-down list through shiny, using atomic vector
Rshiny output is duplicated on both tab panels
Optimizing a shiny server.R code
Error in if: the condition has length > 1.
Position of button changes as soon as i hit the button
R shiny: filtering function does not work after manual data upload
How to make a simple Shiny with radio buttons, followed by drop down menu's and a interactive histogram of the previous made choises?
weblink:3838/myapps
Is there an upper limit of code in R
Can't Deploy machine learning model
Error on Shiny app
Problem with my shiny app. Does not return a plot
I am not able to create a ggplot in Shiny Application.
Validate field to allow file upload - files are uploading twice
shiny app reloading any time I download plot
How to use selectInput with an editable DT table
r + ML : predict()
Making a Shiny app with a conditional Panel and a checkbox.
Unable to connect to RShiny
Save rective values
Dynamic min max values for inputslider R
Adding text description at the bottom/top of the plot in tab panel in R shiny
Multiple reactive conductors in ggplot call
Warning: Error in [: object of type 'closure' is not subsettable
shp file in the funtion
Creating a shiny app UI for R model
About the shiny category
Rename 3 files with a different name each

I'm replying instead of editing as I'm not sure how to state this in the guide:

One pattern I see is learners have R that's not working and they have it all wrapped up in a Shiny app. I am of the opinion that the best way to get a working Shiny app is to get the basic logic working in R then (and only then) wrap the shiny bits around it. How can we tactfully (or not tactfully) encourage this and help a learner understand that by trying to debug basic R logic inside of a Shiny app is a very slow and hard way to learn R?

14 Likes

Based on some sustainer discussion, some think it would be useful to have a series of guides, (and much of this exists already, though perhaps less geared toward the novice level of shiny-users seeking help here and elsewhere)

  1. Shiny debugging,
  2. Shiny reprex, (suggesting rstudio.cloud to host code)
  3. one for trouble-shooting deployment issues.
  4. Guidance about testing core logic outside of shiny (and how to mock things effectively to do so) and generally encouraging people to get the basic engine working in plain R before compliexifying things with shiny
3 Likes