Jonathan
Jonathan

Reputation: 641

In Shiny, is it possible to select rows from DT, by clicking, as reactive input?

Is there a way to take the DataTable output with its selection and use the ones highlighted as the reactive input for the plot?

 ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  dataTableOutput("table1"),
  verbatimTextOutput("info")
)

server <- function(input, output) {
  output$table1 <- renderDataTable(({mtcars}))
  #figure out a way to reactively select points to point into output$plot1
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })

  output$info <- renderPrint({
    # With base graphics, need to tell it what the x and y variables are.
    nearPoints(mtcars, input$plot_click, xvar = "wt", yvar = "mpg")
    # nearPoints() also works with hover and dblclick events
   })
}

shinyApp(ui, server)

https://shiny.rstudio.com/articles/selecting-rows-of-data.html https://shiny.rstudio.com/gallery/datatables-options.html

Upvotes: 1

Views: 1264

Answers (1)

Mal_a
Mal_a

Reputation: 3760

here is the solution to Your question:

library(shiny)
library(DT)
library(ggplot2)

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  dataTableOutput("table1"),
  verbatimTextOutput("info")
)

server <- function(input, output) {
  output$table1 <- DT::renderDataTable(mtcars)
  #figure out a way to reactively select points to point into output$plot1
  output$plot1 <- renderPlot({
    s = input$table1_rows_selected
    mtcars <- mtcars[ s,]
    ggplot(mtcars, aes(mtcars$wt, mtcars$mpg)) + geom_point()
  })

  output$info <- renderPrint({
    # With base graphics, need to tell it what the x and y variables are.
    nearPoints(mtcars, input$plot_click, xvar = "wt", yvar = "mpg")
    # nearPoints() also works with hover and dblclick events
  })
}

shinyApp(ui, server)

I have used the special function from DT package called: input$table1_rows_selected, which selects the higlighted rows, then i further subset them from the dataset mtcars

Upvotes: 2

Related Questions