AI Kidds
AI Kidds

Reputation: 39

Rshiny did not show any hint in the console so how to debug the Rshiny code?

I found the rshiny script is super hard to debug. Especially, the rshiny bottom is the RunAPP. If I get the error. I did not see any hints from the Console. Could I ask how you guys debug the rshiny?

Thanks

Upvotes: 0

Views: 684

Answers (2)

Phil
Phil

Reputation: 8107

Here is an example of how I debug in Shiny:

library(shiny)

ui <- fluidPage(

    titlePanel("Old Faithful Geyser Data"),

    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

server <- function(input, output) {
    
    x <- reactive({
        faithful[, 2]
    })
    
    bins <- reactive({
        seq(min(x()), max(x()), length.out = input$bins + 1)
    })
    
    observe(print(bins())) # THIS LINE WILL PRINT OUTPUT TO CONSOLE

    output$distPlot <- renderPlot({
        hist(x(), breaks = bins(), col = 'darkgray', border = 'white')
    })
}

shinyApp(ui = ui, server = server)

The observe(print(reactive_object_name())) will print a reactive object to the console, which allows you to inspect what happens to a reactive object when you change inputs in the app.

Upvotes: 2

Jan
Jan

Reputation: 5254

Most of all: always keep in mind that you need to test and debug your code. Do not just write code to satisfy requirements. Consider testing and debugging to be a requirement itself. That mind set is a good starting point to follow these rules:

  1. R-Studio provides quite some functionality useful for debugging: step-by-step execution of your code, a trace of function calls, inspection of variables, and the opportunity to run your own code on the console while the app is on hold.
  2. If breakpoints do not work (sometimes they just won't), add browser() to your code which creates a "forced" breakpoint.
  3. Sometimes print() helps getting additional information output to the console.
  4. Clearly separate the business logic from the UI. Use unit tests (testthat). If errors occur, write some sample code to test the business logic outside the shiny app.

Upvotes: 2

Related Questions