cho7tom
cho7tom

Reputation: 1070

Shiny renderDataTable | how to limit text size displayed

While displaying a data table in shiny

output$tab1 <- renderDataTable({
expr = tbl
}, options = list(orderClasses = TRUE,
                  lengthMenu = c(3, 5, 10),
                  pageLength = 3)

I would like to limit the text in each cell to 30 characters. Is there an option for that in order to facilitate the reading?

I tried the solution of package DT (http://rstudio.github.io/DT/, see section 2.5.4 column rendering) but I was unsuccessful (I want to use renderDataTable with my current list of options)

Many thanks in advance for your help!

Regards,

Thomas

Upvotes: 4

Views: 2962

Answers (2)

Nivel
Nivel

Reputation: 679

Another option would be to mutate your column to shorten any strings with more than 30 characters.

library(dplyr)
library(stringr)

tbl <- tbl %>% mutate(column_name = as.character(column_name)) %>% 
               rowwise() %>% 
               mutate(column_name = case_when(nchar(column_name) > 30 ~
               paste(str_sub(column_name, 1, 30), "..."),
               nchar(column_name) <= 30 ~ column_name))  

This will shorten all strings to 30 characters and add a ... at the end.

Upvotes: 1

user5249203
user5249203

Reputation: 4648

Not sure if you still looking for the answer. But, it is pretty easy to include a tool tip using the example below. You can find this example and more in this link https://rstudio.github.io/DT/options.html

datatable(iris[c(1:20, 51:60, 101:120), ], options = list(columnDefs = list(list(
  targets = 5,
  render = JS(
    "function(data, type, row, meta) {",
    "return type === 'display' && data.length > 6 ?",
    "'<span title=\"' + data + '\">' + data.substr(0, 6) + '...</span>' : data;",
    "}")
))), callback = JS('table.page(3).draw(false);'))

Upvotes: 4

Related Questions