Nic
Nic

Reputation: 15

R Shiny does not display the output data table

I cannot see the data table as output, neither the whole data, nor the selected with the reactive function.The dataset is generated inside the Shiny app by the function Merton. I tried to use several object classes for the dataset "mod", but it did not work. Here's the code:

 library(shiny)
 server <- function(input,output, session) {

      library(ggplot2) 
      library(DT) 
      library(CreditRisk)

      Maturity <- c(0.5, 1, 2, 3, 5, 10, 15, 20, 25, 30, 35)
      mod <- Merton(L = 10, V0 = 20, sigma = 0.2, r = 0.005, t = Maturity)


      output$plot <- renderPlot({

        ggplot(mod, aes(Maturity, mod$Surv))+ geom_point()

      })


      dat <- reactive({

        user_brush <- input$user_brush
        sel.data <- brushedPoints(mod, user_brush)
        return(sel.data)

      })


      output$table <- DT::renderDataTable(DT::datatable(dat()))

      output$mydownload <- downloadHandler(
        filename = "plotextract.csv",
        content = function(file) {
          write.csv(dat(), file)})
    }

    ui <- fluidPage(

      h3("Exporting Data as .csv"),
      plotOutput("plot", brush = "user_brush"),
      dataTableOutput("table"),
      downloadButton(outputId = "mydownload", label = "Download Table")
    )

    shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 2526

Answers (1)

pogibas
pogibas

Reputation: 28379

You have to pass xvar and yvar to brushedPoints:
brushedPoints(mod, user_brush, xvar = "Maturity", yvar = "Survival")

For simplicity I change corresponding variables in ggplot: aes(Maturity, Survival)

library(shiny)

server <- function(input,output, session) {

    library(CreditRisk)
    library(DT) 
    library(ggplot2) 

    Maturity <- c(0.5, 1, 2, 3, 5, 10, 15, 20, 25, 30, 35)
    mod <- Merton(L = 10, V0 = 20, sigma = 0.2, r = 0.005, t = Maturity)

    output$plot <- renderPlot({
        ggplot(mod, aes(Maturity, Survival)) + geom_point()
    })

    dat <- reactive({
        user_brush <- input$user_brush
        brushedPoints(mod, user_brush, xvar = "Maturity", yvar = "Survival")
    })

    output$table <- DT::renderDataTable({DT::datatable(dat())})

    output$mydownload <- downloadHandler(
        filename = "plotextract.csv",
        content = function(file) {write.csv(dat(), file)}
    )
}

ui <- fluidPage(
    h3("Exporting Data as .csv"),
    plotOutput("plot", brush = "user_brush"),
    dataTableOutput("table"),
    downloadButton(outputId = "mydownload", label = "Download Table")
)

shinyApp(ui = ui, server = server)

enter image description here

Upvotes: 1

Related Questions