[英]R DT::datatables formatting multiple columns simultaneously
我希望在一個閃亮的儀表板上同時跨多個列實現formatCurrency()
和formatPercentage()
(均來自DT包)。 對於給定的示例,我正在使用Shinymaterial。
我目前正在執行以下操作:
# The packages to load.
required_packages <- c("shiny", "shinymaterial", "DT", "tidyverse")
# This function will load in all the packages needed.
lapply(required_packages, require, character.only = TRUE)
# A table example.
ui <- material_page(
title = "Example table",
tags$h1("Table example"),
material_card(
title = "Table",
material_row(
DT::dataTableOutput("data_table_example")
),
depth = 1
)
)
server <- function(input, output) {
data_table_example_data = tibble(
Person = paste0("Person ", c(1:100)),
`Price $` = rnorm(100, 50000, 500),
`Cost $` = rnorm(100, 30000, 300),
`Probability %` = rnorm(100, 0.6, 0.1),
`Win %` = rnorm(100, 0.5, 0.2)
)
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency("Price $") %>%
formatCurrency("Cost $") %>%
formatPercentage("Probability %", digits = 1) %>%
formatPercentage("Win %", digits = 1)
})
}
shinyApp(ui = ui, server = server)
但是,我想做的是在renderDataTable()
函數中,將格式函數簡化為更少的行。 例如,實施formatCurrency()
中的任何一列以“$”和formatPercentage()
中的任何一列用“%”。
我已經做了相當多的尋找適當的解決方案,但是找不到解決方案,但是我想我只是缺少一個相當簡單的解決方案。
就像是:
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency(grepl("$", colnames()) %>%
formatPercentage(grepl("%", colnames()), digits = 1)
})
其他幾點:
任何幫助將不勝感激
嘗試:
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency(grepl("$", colnames(data_table_example_data)) %>%
formatPercentage(grepl("%", colnames(data_table_example_data)), digits = 1)
})
似乎您需要對數據進行明確顯示,因此colnames()
不起作用-您需要colnames(data_table_example_data)
。
我在測試過程中注意到,如果您將grepl
與grepl
rownames = TRUE
一起使用,則grepl
會成為第一列名稱,這意味着所有格式都被一一排除。 grep
似乎沒有這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.