R shiny 数据表 - 当字符列包含很长的字符串时强制行高

R shiny datatable - force rows height when a character column contains very long strings

我正在用 R 构建一个闪亮的应用程序,并面临以下示例代码最能描述的问题:

library(shiny)
library(shinydashboard)
library(shinyBS)
library(dplyr)
library(lubridate)
library(DT)

ui <- fluidPage(
  
  mainPanel(
    h3("Table:"),
    dataTableOutput("sample_table1")
  )
  
)

server <- function(input, output, session) {   
  
  output$sample_table1 <- renderDataTable({  #
    df <- head(mtcars, 5)
    
    df$NEW_COL1 <- c("This is an example showing that this row will be displayed with a very wide height because this text is too long",
                     "hello","hello","hello","hello")
    
    df$color <- "blue"
    df$city <- "Kansas"
    df$second_color <- "yellow"
    
    df <- datatable(df,
                    filter = 'top',
                    rownames= FALSE,
                    options = list(scrollX = TRUE
                                   , searching = FALSE
                                   , pageLength = 5
                    )) 
  })
}


cat("\nLaunching   'shinyApp' ....")
shinyApp(ui, server)

如果你 运行 这个应用程序,你会看到第一行的高度变得疯狂,因为列“NEW_COL1”中的字符串的长度太长了。 我的两个问题是:

  1. 有没有办法强制每行的高度为 1(1 表示与第二行的高度相同),无论第 NEW_COL1 列中的字符串有多长?

  2. 如果第 1 点的答案是否定的,我想简单地对该行中的数据进行子字符串化。在这种情况下,是否可以通过将鼠标悬停在 table?

    的单元格上来查看每个单元格中的完整字符串

我发现的某种相关的 post 是以下 但 none 那里提供的解决方案可以满足我的需要。 谢谢

对于第二个选项,您可以使用此 question 中的代码:

    df <- datatable(
        df,
        filter = 'top',
        rownames = FALSE,
        options = list(
            scrollX = TRUE,
            searching = FALSE,
            pageLength = 5,
            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;",
                    "}"
                )
            ))
        )
    )