我希望在一个闪亮的仪表板上同时跨多个列实现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)
})
其他几点:
任何帮助将不胜感激
答案 0 :(得分: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
与rownames = TRUE
一起使用,则行名将成为第一列名,这意味着所有格式都将被一一排除。 grep
似乎没有这个问题。