3

I have a data table with a lot of text in some rows.

What I would like to do is to limit the default display of text in the row to 4 lines and then when the row is clicked to either expand it, or only display that specific row.

library(shiny)
library(DT)

data <- data.frame(
  question = c("question1", "question2", "guestion3", paste0("A ", paste0(rep("very", 1000), collapse = " "), "long question"), "..."),
  answer = c("answer1", "answer2", paste0("A ", paste0(rep("very", 1000), collapse = " "), "long answer"),
             paste0("Another ", paste0(rep("very", 200), collapse = " "), "long answer"), "...")
)

ui <- fluidPage(
  DT::dataTableOutput(('DTOut'))
)

server <- function(input, output) {

  output$DTOut <- DT::renderDataTable({
    data
  })
}

shinyApp(ui = ui, server = server)

I was trying to play with max-height and toggle, however wasn't very successful there.

1 Answers1

2

Here is a solution from the DT page. But it uses the number of characters and the remaining text it shows when hovering over the cell.

datatable(data, options = list(columnDefs = list(list(
  targets = c(1,2),
  render = JS(
   "function(data, type, row, meta) {",
   "return type === 'display' && data.length > 100 ?",
   "'<span title=\"' + data + '\">' + data.substr(0, 100) + '...</span>' : data;",
   "}")
))))
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
  • This breaks when there are NAs in the desired column. Try `dt[is.na(dt)] <- ""` before using – hedgedandlevered Apr 04 '19 at 19:40
  • apparently the code in `options` is run before the code in `data`, which has important ramifications in Shiny (if you are using a reactive variable to define "targets"), or anywhere where order may matter – hedgedandlevered Apr 05 '19 at 15:06
  • @hedgedandlevered if you have a new implementation/scenario then please ask a new question amd linked to this question if its help. – A. Suliman Apr 05 '19 at 15:22
  • 1
    I'm just commenting on some more specific implementations of this problem; corner cases that may result in unintended behavior I found. People using shiny are likely to use this function, so just helping where I ran into an issue. If you want to make a new question, I'll answer that. – hedgedandlevered Apr 05 '19 at 15:54