[英]Shiny DataTable column width by name
I have a DataTable in a Shiny app and the user is allowed to select the columns.我在 Shiny 应用程序中有一个 DataTable,并且允许用户选择列。 I want to control the width of the column but that column's index changes depending on user selections so I want to control the width based on the column name.我想控制列的宽度,但该列的索引根据用户选择而变化,所以我想根据列名控制宽度。
In the reproducible example below (which is just an example of what I want to do), I would like to control the width of column "c".在下面的可重现示例中(这只是我想要做的一个示例),我想控制“c”列的宽度。 At first I know the index so this is fine, but when the user adds a new column ("b") the column width formatting gets applied to whatever column is second (index = 1 ).起初我知道索引所以这很好,但是当用户添加新列(“b”)时,列宽格式将应用于第二列(索引 = 1)。
Note that the documentation for DataTables suggests that using target=c("c")
would be possible but this link seems to say that the functionality does not work.请注意,DataTables 的文档建议使用target=c("c")
是可能的,但此链接似乎表明该功能不起作用。
library(shiny)
ui <- shinyUI(
tagList(
navbarPage(title = HTML('<span class="navtitle">Test</span>'),
id= "myid",
inverse=TRUE,
collapsible = TRUE,
tabPanel("Home",
selectInput('myselect', label="", choices=c("a", "b", "c"),
selected = c("a", "c"), multiple=TRUE),
dataTableOutput(outputId="dataTable")
)
)
)
)
server <- function(input, output, session){
output$dataTable <- renderDataTable({
dat <- data.frame(a=1:10, b=1:10, c=1:10)
dat[, names(dat)%in%input$myselect]
},
options = list(pageLength = 100, dom='frtp',
scrollX = TRUE,
columnDefs = list(list(width = '30px', targets = c(1))))
)
}
shinyApp(ui=ui, server=server)
Thanks to @Yihui for the answer at this post感谢@Yihui 在这篇文章中的回答
You can use a function in the options, very useful您可以在选项中使用一个功能,非常有用
library(shiny)
ui <- shinyUI(
tagList(
navbarPage(title = HTML('<span class="navtitle">Test</span>'),
id= "myid",
inverse=TRUE,
collapsible = TRUE,
tabPanel("Home",
selectInput('myselect', label="", choices=c("a", "b", "c"),
selected = c("a", "c"), multiple=TRUE),
dataTableOutput(outputId="dataTable")
)
)
)
)
server <- function(input, output, session){
output$dataTable <- renderDataTable({
dat <- data.frame(a=1:10, b=1:10, c=1:10)
dat[, names(dat)%in%input$myselect]
},
options = function(){
indx <- c(which("b"%in%input$myselect))
if(length(indx)==0) index <- ''
list(
pageLength = 100,
dom='frtp',
scollX = TRUE,
columnDefs = list(list(width = '30px', targets = indx))
)
}
)
}
shinyApp(ui=ui, server=server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.