Sumchans
Sumchans

Reputation: 3774

Select and display the value of a row in Shiny Datatable

I am totally new to R & Shiny, this would be my first project, which I was able to get to this point after going through some awesome tutorials.

I am trying a have the value of the selected row display in the textOutput. The code works with the selection, but I am not able to display the value of the selected row to the textOuput, as it shows [Object Object].

This is what I got so far:

library(shiny)
library(data.table)
addr <- as.data.table(read.csv("addresses.csv", header = T, stringsAsFactors = F))
names(addr) [1:4]<- c("STREET ADDRESS","CITY NAME","PROVINCE","POSTAL CODE")

ui <- fluidPage(
  br(),
  fluidRow(
    column(12, div(DT::dataTableOutput("addressTable"), style="font-family:verdana", align="left"))
  ),
  fluidRow(
    column(4, div(textOutput("selectedAddress"), align="center"))
  )
)

server <- function(input, output) {
  output$addressTable <- DT::renderDataTable({addr}, server = T, selection = 'single')

  output$selectedAddress <- DT::renderDataTable({
    selectedrowindex <<-input$addr_rows_selected
    selectedrowindex <<-as.numeric(selectedrowindex)
    selectedrow <- (addr[selectedrowindex,])
    selectedrow
  })
}

shinyApp(ui, server)

Upvotes: 0

Views: 1856

Answers (1)

Wil
Wil

Reputation: 3178

A few adjustments:

  1. Your syntax for accessing the selected rows was off slightly. From the data.table documentation, the input is access with the ID passed to the dataTableOutput(); where you wrote input$addr_rows_selected you actually want input$addressTable_rows_selected in order to find the table rendered with DT::dataTableOutput("addressTable").
  2. You are mixing output types with render types. If you want the address to be output as text (per the line textOutput("selectedAddress")) then you should use renderText() rather than DT::renderDataTable().
  3. In order to render the address as text, you must take the address (components) and collapse it down to a character string, which can be done with paste(...,collapse = ",")
library(shiny)
library(data.table)
addr <- as.data.table(read.csv("addresses.csv", header = T, stringsAsFactors = F))
names(addr) [1:4]<- c("STREET ADDRESS","CITY NAME","PROVINCE","POSTAL CODE")

ui <- fluidPage(
  br(),
  fluidRow(
    column(12, div(DT::dataTableOutput("addressTable"), style="font-family:verdana", align="left"))
  ),
  fluidRow(
    column(4, div(textOutput("selectedAddress"), align="center"))
  )
)

server <- function(input, output) {
  output$addressTable <- DT::renderDataTable({addr}, server = T, selection = 'single')

  output$selectedAddress <- renderText({
    selectedrowindex <- input$addressTable_rows_selected
    selectedrowindex <- as.numeric(selectedrowindex)
    selectedrow <- paste(addr[selectedrowindex,],collapse = ", ")
    selectedrow
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions