![](/img/trans.png)
[英]How to color multiple cells in Data table given their row and column indexes in R shiny, with different colors
[英]How to set column width in R Shiny data table?
我正在构建一个显示数据表的闪亮仪表板。
我的目标是自动调整数据表的列宽以适应 1 行而不是多行中的单元格值。 但是,我得到了以下结果:
似乎Name被调整为我想要的,但Notes没有。 然后,我按照这些链接: https://rstudio.github.io/DT/options.html ,
在很多列的情况下,在 R Shiny DataTable 中设置列宽不起作用,
基本上,在线建议的解决方案是在呈现数据表时使用autoWidth = TRUE
参数和columnDefs
。
这对我也不起作用,结果如下:
与初始结果相比,表格的宽度似乎变窄了
下面是我的最终代码:
header <- dashboardHeader(
title = "Test"
)
sidebar <- dashboardSidebar(
)
body <- dashboardBody(
box(title = "Test", width = 7, status = "warning", DT::dataTableOutput("df"))
)
# UI
ui <- dashboardPage(header, sidebar, body)
# Server
server <- function(input, output, session) {
output$df = DT::renderDataTable(df, options = list(
autoWidth = TRUE,
columnDefs = list(list(width = '10px', targets = c(1,3)))))
}
# Shiny dashboard
shiny::shinyApp(ui, server)
我不知道为什么Name列的宽度可以随单元格值的长度调整,而Notes的宽度则不能。 我也尝试过在其他项目中使用数据表,列的宽度只能通过列名的长度来调整。
在我的情况下,另一个选项是将列宽设置为只有一定数量的字符,并通过将鼠标悬停在单元格上来显示单元格值的完整上下文。 此处建议了解决方案: R Shiny Dashboard DataTable Column Width 。 然而,这仅适用于 DT,但当我将它集成到 Shiny 中时它不起作用。
提前致谢。
如果您不想要多行,您可以将 CSS 属性white-space: nowrap
到您想要的列中的单元格。
因为你在 Shiny 中,所以很容易做到这一点,通过定义一个 CSS 类并将它分配给columnDefs
选项中带有className
的列:
library(DT)
library(shiny)
dat <- data.frame(
V1 = c("A", "B"),
V2 = c(
"A cool guy living in US and Canada",
"A cool guy living in California"
),
V3 = c(
"A cool guy living in US and Canada",
"A cool guy living in California"
),
V4 = c(
"A cool guy living in US and Canada",
"A cool guy living in California"
),
V5 = c(
"A cool guy living in US and Canada",
"A cool guy living in California"
),
stringsAsFactors = FALSE
)
css <- "
.nowrap {
white-space: nowrap;
}"
ui <- fluidPage(
tags$head(
tags$style(HTML(css))
),
DTOutput("table")
)
server <- function(input, output){
output[["table"]] <- renderDT({
datatable(dat,
options = list(
columnDefs = list(
list(className = "nowrap", targets = "_all")
)
))
})
}
shinyApp(ui, server)
问题是列宽的索引是基数 0,而不是 1。在 OP 代码中,目标设置了第 2 列和第 4 列的宽度(相对较窄的 10px),而不是 1 和 3。
尝试以下,
columnDefs = list(list(width = '200px', 目标 = c(0,2)))))
这应该使第一列和第三列为 200 像素,而所有其他列都是自动宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.