【问题标题】:Passing column name to target option in a shiny datatable将列名传递给闪亮数据表中的目标选项
【发布时间】:2019-03-28 15:19:48
【问题描述】:

我一直在尝试在 columnDefs 的目标选项中传递列名(而不是列号)。该表是动态的,所以我绝对需要选择以列名为目标。下面是一个可重现的例子。但是,该示例不是动态的。

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);'))

尝试使用 targets = 'Species'targets = iris$Species 但它们不起作用。

【问题讨论】:

  • 也许targets = which(names(iris)=="Species") ?
  • 这是完美的。工作得很好。只是一个建议:在动态表中,代码必须指向子集数据框而不是原始数据框。例如,如果"columns" 是应用程序中的输入:cols &lt;- as.numeric(input$columns) which(names(iris[,cols])=="Species" 但是,如果您将评论作为答案,我会接受,谢谢 :D

标签: r datatable shiny


【解决方案1】:

如果您有兴趣将多个列设置为不同的宽度,请考虑以下事项(注意 R 是基于一的,而 javascript 是基于一的):

  col_a <- which(names(dat) %in% c("column_name1", "column_name2"))
  col_b <- which(names(dat) %in% c("column_name3", "column_name4"))
  col_c <- which(names(dat) %in% c("column_name5"))

  columnDefs = list(list(width = '30px', targets = as.list(col_a - 1)),
                    list(width = '80px', targets = as.list(col_b - 1)),
                    list(width = '200px', targets = as.list(col_c - 1)))

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2016-08-13
    相关资源
    最近更新 更多