Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row values from selected row in a Data Table in R Shiny App

I need to get the selected row 1st column value from the DT Data Table. Using, DataTable_rows_selected , I am able to get the selected row count, Now I am looking for ways to extract the row values from the data table. In the example below, there are two observeEvent based on action button, 1st observe event is import and displays the data and 2nd one needs to display the selected row 1st col value so that I can use the same achieve other features. Please note,In Actual Application, the imported data is a web service API and which I am parsing in R and converting to data frame.

Sample Example:

library(shiny)
library(shinydashboard)
library(DT)

ui <- dashboardPage(
dashboardHeader(title = "Data Table Example"),
dashboardSidebar(
sidebarMenu(
  menuItem('Tabs', tabName='tabs',
           menuSubItem('Tab 1', tabName='tab1'),
           menuSubItem('Tab 2', tabName='tab2')
  )
)
),

dashboardBody(

tabItems(
  tabItem(tabName='tab1',
          actionButton("import","Import"),
          br(),
          tags$div(tags$h3(tags$b(" Get Selected Row Values",align="middle",style="color: rgb(57,156,8)"))),
          br(),
          DT::dataTableOutput('ProductDataTable')
  ),
  tabItem(tabName='tab2',
          actionButton("display","Display"),
          uiOutput('info')
   )
 )
 )
 )

server <- function(input, output) {

observeEvent(input$import,{

Product <- read.csv2("RulesData.csv", header=TRUE, sep=";")

output$ProductDataTable <- DT::renderDataTable({

DT::datatable(Product,selection = "single",

                extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                rownames=FALSE,
                options=list(dom = 'Bfrtip',
                             searching = T,
                             pageLength = 25,
                             searchHighlight = TRUE,
                             colReorder = TRUE,
                             fixedHeader = TRUE,
                             filter = 'bottom',
                             buttons = c('copy', 'csv','excel', 'print'),
                             paging    = TRUE,
                             deferRender = TRUE,
                             scroller = TRUE,
                             scrollX = TRUE,
                             scrollY = 700

                ))
})

})

observeEvent(input$display,{

row_count <- input$ProductDataTable_rows_selected

output$info <- renderPrint({

  cat('Row Selected: ')
  cat(row_count, sep = ', ')
  cat(Product[1,2], sep = ', ')


 })

})
}

shinyApp(ui, server)
like image 980
string Avatar asked Oct 19 '25 02:10

string


2 Answers

check this code below if this is what You are looking for:

library(shiny)
library(shinydashboard)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Data Table Example"),
  dashboardSidebar(
    sidebarMenu(
      menuItem('Tabs', tabName='tabs',
               menuSubItem('Tab 1', tabName='tab1'),
               menuSubItem('Tab 2', tabName='tab2')
      )
    )
  ),

  dashboardBody(

    tabItems(
      tabItem(tabName='tab1',
              actionButton("import","Import"),
              br(),
              tags$div(tags$h3(tags$b(" Get Selected Row Values",align="middle",style="color: rgb(57,156,8)"))),
              br(),
              DT::dataTableOutput('ProductDataTable')
      ),
      tabItem(tabName='tab2',
              actionButton("display","Display"),
              uiOutput('info')
      )
    )
  )
)

server <- function(input, output) {

  Product <- reactive({mtcars})

  observeEvent(input$import,{


    output$ProductDataTable <- DT::renderDataTable({

      DT::datatable(Product(),selection = "single",

                    extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                    rownames=FALSE,
                    options=list(dom = 'Bfrtip',
                                 searching = T,
                                 pageLength = 25,
                                 searchHighlight = TRUE,
                                 colReorder = TRUE,
                                 fixedHeader = TRUE,
                                 filter = 'bottom',
                                 buttons = c('copy', 'csv','excel', 'print'),
                                 paging    = TRUE,
                                 deferRender = TRUE,
                                 scroller = TRUE,
                                 scrollX = TRUE,
                                 scrollY = 700

                    ))
    })

  })

  observeEvent(input$display,{


    output$info <- renderPrint({
      row_count <- input$ProductDataTable_rows_selected
      data <- Product()[row_count, ] 
      cat('Row Selected: ')
      cat(data[,1]) #display the selected row 1st col value  


    })

  })
}

shinyApp(ui, server)

I have used mtcars dataset as an example, the problem was that Your data was inside of the observer (one with input$import) and as You need to use it for other analysis such as displaying of the row value of first column (i have not understood well what did You mean about that as Your code is telling different thing), data had to be moved outside of the observer and put into reactive.

[UPDATE]

I have used if statement to import the data instead of observeEvent

library(shiny)
library(shinydashboard)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Data Table Example"),
  dashboardSidebar(
    sidebarMenu(
      menuItem('Tabs', tabName='tabs',
               menuSubItem('Tab 1', tabName='tab1'),
               menuSubItem('Tab 2', tabName='tab2')
      )
    )
  ),

  dashboardBody(

    tabItems(
      tabItem(tabName='tab1',
              actionButton("import","Import"),
              br(),
              tags$div(tags$h3(tags$b(" Get Selected Row Values",align="middle",style="color: rgb(57,156,8)"))),
              br(),
              DT::dataTableOutput('ProductDataTable')
      ),
      tabItem(tabName='tab2',
              actionButton("display","Display"),
              uiOutput('info')
      )
    )
  )
)

server <- function(input, output) {

  Product <- reactive({
    if(input$import == 0)
  {
    return()
  }
    isolate({
      input$import
      data <- mtcars # Here read Your data: read.csv2("RulesData.csv", header=TRUE, sep=";")
      })
  })


    output$ProductDataTable <- DT::renderDataTable({

      DT::datatable(Product(),selection = "single",

                    extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                    rownames=FALSE,
                    options=list(dom = 'Bfrtip',
                                 searching = T,
                                 pageLength = 25,
                                 searchHighlight = TRUE,
                                 colReorder = TRUE,
                                 fixedHeader = TRUE,
                                 filter = 'bottom',
                                 buttons = c('copy', 'csv','excel', 'print'),
                                 paging    = TRUE,
                                 deferRender = TRUE,
                                 scroller = TRUE,
                                 scrollX = TRUE,
                                 scrollY = 700

                    ))
    })


  observeEvent(input$display,{


    output$info <- renderPrint({
      row_count <- input$ProductDataTable_rows_selected
      data <- Product()[row_count, ] 
      cat('Row Selected: ')
      cat(data[,1]) #display the selected row 1st col value  


    })

  })
}

shinyApp(ui, server)
like image 84
Mal_a Avatar answered Oct 21 '25 17:10

Mal_a


one more way to get row values from Data Table is DT:DataTable Call Back option in association with Java Script JS().

Here is the code:

library(shiny)
library(shinydashboard)
library(DT)

ui <- dashboardPage(
dashboardHeader(title = "Data Table Example"),
dashboardSidebar(
sidebarMenu(
  menuItem('Tabs', tabName='tabs',
           menuSubItem('Tab 1', tabName='tab1'),
           menuSubItem('Tab 2', tabName='tab2')
  )
)
),

dashboardBody(

tabItems(
  tabItem(tabName='tab1',
          actionButton("import","Import"),
          br(),
          tags$div(tags$h3(tags$b("Get Selected Row Values",style="color: rgb(57,156,8)"))),
          br(),
          DT::dataTableOutput('ProductDataTable')
  ),
  tabItem(tabName='tab2',
          actionButton("display","Display"),
          uiOutput('info')
  )
)
)
)

server <- function(input, output) {

observeEvent(input$import,{

Product <- mtcars

output$ProductDataTable <- DT::renderDataTable({

  DT::datatable(Product,selection = "single",
  # JS using call back function to get the row values on single click
                callback = JS("table.on('click.dt', 'tr',
                  function() {
                  Shiny.onInputChange('rows', table.rows(this).data().toArray());
                  });"),

                extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                rownames=FALSE,
                options=list(dom = 'Bfrtip',
                             searching = T,
                             pageLength = 25,
                             searchHighlight = TRUE,
                             colReorder = TRUE,
                             fixedHeader = TRUE,
                             filter = 'bottom',
                             buttons = c('copy', 'csv','excel', 'print'),
                             paging    = TRUE,
                             deferRender = TRUE,
                             scroller = TRUE,
                             scrollX = TRUE,
                             scrollY = 700

                ))
})

})

observeEvent(input$display,{

row_count <- input$ProductDataTable_rows_selected

output$info <- renderPrint({
  cat('Row Selected 1st Col Value: ')
  # getting 1st row col value
  cat(input$rows[1], sep = ', ')

})

})
}

shinyApp(ui, server)
like image 34
string Avatar answered Oct 21 '25 16:10

string



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!