在Shiny中,是否可以通过单击作为反应输入从DT中选择行?

时间:2017-03-02 20:32:23

标签: r dataframe shiny

有没有办法将DataTable输出与其选择一起使用,并使用突出显示为绘图的反应输入的输出?

 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

1 个答案:

答案 0 :(得分:1)

这是您的问题的解决方案:

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)

我使用了名为DT的{​​{1}}包中的特殊功能,它选择了高亮显示的行,然后我从数据集input$table1_rows_selected进一步对它们进行了子集