How to Truncate text in DataTable in R Shiny?

耗尽温柔 提交于 2021-02-10 07:44:50

问题


I am using DataTable in Rshiny app to display the content of the Dataframe. But one element of the dataframe is of text, can have characters more than 1000. When I am displaying the datatable it shows all the text. I want to truncate it to first 250 characters and when hover it should show the full text. How can I do that?

ui.r

shinyUI(fluidPage(
  theme = shinythemes::shinytheme("flatly"),
  titlePanel("title"),
  sidebarLayout(
    sidebarPanel(
      width=0
    ),
    mainPanel(
      width=12,
      tabsetPanel(tabPanel("Data",DT::dataTableOutput("train_data",width = "100%")))
  )
  )
))

server.r

output$train_data <- renderDataTable({
 if(is.null(camry_data$train_data)){return ()}
    DT::datatable(camry_data$train_data, options = list(lengthMenu = c(5,10)),class = "display")
  })

回答1:


I closely followed section 4.4 Column Rendering here with a few tweaks: https://rstudio.github.io/DT/options.html

Also, the targets parameter can be set to a vector of column indexes, e.g. c(1,3,5)

output$train_data <- renderDataTable({
 if(is.null(camry_data$train_data)){return ()}
    DT::datatable(camry_data$train_data, options = list(lengthMenu = c(5,10),
    columnDefs = list(list(
      targets = "_all",
      render = JS(
        "function(data, type, row, meta) {",
        "return type === 'display' && data != null && data.length > 30 ?",
        "'<span title=\"' + data + '\">' + data.substr(0, 30) + '...</span>' : data;",
        "}")
      ))),
      class = "display")
})


来源:https://stackoverflow.com/questions/49247508/how-to-truncate-text-in-datatable-in-r-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!