简体   繁体   中英

Capture rows selected from shiny table

Is there a way to capture the values based on rows selected from First table. RIght now, what is happening is only based on rows names, the values are popped on the second table. But these are incorrect. Please see below

在此处输入图片说明

library(shiny)
library(DT)
library(dplyr)

asd <- data.frame(a = c(7,7,8,8,2,1,3,5,5,6), b = c("A","B","C","A","B","C","A","B","C","F"))
ui <- fluidPage(
  selectInput("sel","Slect",choices = asd$b),
  dataTableOutput("tab"),
  dataTableOutput("txt")
)

server <- function(input, output, session) {
  
  ## First table
  output$tab <- renderDataTable({
    asd <- asd %>% filter(b %in% input$sel)
    datatable(asd,selection = 'single')
  })
  
  
  
  ## Second table
  output$txt <- renderDataTable({
    datatable(asd[rownames(asd) == input$tab_rows_selected,])
  })
  
}

shinyApp(ui, server)

Your problem is that you are running a filter in your output$tab, but not in output$txt, so the indices are not the same. You are pulling the 'second row' in your selection, so it is giving you the 'second row' in asd, but the two are not the same.

Simple solution: make them the same. In your output$txt, add one line, the same line you use to filter your dataframe in output$tab

output$txt <- renderDataTable({
    asd <- asd %>% filter(b %in% input$sel)
    datatable(asd[rownames(asd) == input$tab_rows_selected,])
  })

This works as expected.

Edit: If your use case is more complex, and you need to know which row in the original was selected, you can add some kind of 'ID' column and check against that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM