我在Microsoft Excel中有一些表需要在R Shiny App中重新创建。 R中的格式必须至少与原始上下文保持一致。
以下是原始表格的图片:
表1
表2
请注意格式:表格标题下方有行以及总计,标题和总计都是粗体,“每月帐单”列中的数字有数千个用逗号分隔并带有美元符号,表2中的最终数字用于输入。
如果线路不可重新训练,那就没问题了,但我至少需要能够加粗选定的主题,标题和总数,并且能够获得每月账单列的正确数字格式。
我尝试过使用DT包,但我无法弄清楚如何格式化行而不是列。我注意到DT使用JavaScript函数的包装器,但我自己并不亲自了解JavaScript。有没有办法通过R包或Javascript以我需要的方式格式化这个?
编辑:
虽然这很简单,但我不能只包括表格的图像,因为有些数字会链接到用户输入,并且必须能够更新。
答案 0 :(得分:3)
pixiedust
可以轻松进行特定于细胞的自定义。
T1 <- data.frame(Charge = c("Environmental", "Base Power Cost",
"Base Adjustment Cost", "Distribution Adder",
"Retail Rate Without Fuel", "Fuel Charge Adjustment",
"Retail Rate With Fuel"),
Summer = c(0.00303, 0.06018, 0.00492, 0.00501, 0.07314,
0.02252, 0.09566),
Winter = c(0.00303, 0.05707, 0.00468, 0.01264, 0.07742,
0.02252, 0.09994),
Transition = c(0.00303, 0.05585, 0.00459, 0.01264,
0.07611, 0.02252, 0.09863),
stringsAsFactors = FALSE)
T2 <- data.frame(Period = c("Summer", "Winter", "Transition", "Yearly Bill"),
Rate = c(0.09566, 0.09994, 0.09863, NA),
Monthly = c(118.16, 122.44, 121.13, 1446.92),
stringsAsFactors = FALSE)
library(shiny)
library(pixiedust)
library(dplyr)
options(pixiedust_print_method = "html")
shinyApp(
ui =
fluidPage(
uiOutput("table1"),
uiOutput("table2")
),
server =
shinyServer(function(input, output, session){
output$table1 <-
renderUI({
dust(T1) %>%
sprinkle(rows = 1,
border = "bottom",
part = "head") %>%
sprinkle(rows = c(5, 7),
cols = 2:4,
border = "top") %>%
sprinkle(rows = c(5, 7),
bold = TRUE) %>%
sprinkle(pad = 4) %>%
sprinkle_colnames(Charge = "") %>%
print(asis = FALSE) %>%
HTML()
})
output$table2 <-
renderUI({
T2 %>%
mutate(Monthly = paste0("$", trimws(format(Monthly, big.mark = ",")))) %>%
dust() %>%
sprinkle(rows = 1,
border = "bottom",
part = "head") %>%
sprinkle(rows = 4,
cols = 1,
bold = TRUE) %>%
sprinkle(rows = 4,
cols = 3,
border = "all") %>%
sprinkle(na_string = "",
pad = 4) %>%
sprinkle_colnames(Period = "",
Monthly = "Monthly Bill") %>%
print(asis = FALSE) %>%
HTML()
})
})
)
答案 1 :(得分:1)
如果您提供了一个数据示例,但如果坚持使用DT
,则应该能够利用formatStyle
来更改行和列的格式,这会更容易。有关加粗第一行的示例,请参阅以下内容(假设您的数据框名为df
):
df %>%
datatable() %>%
formatStyle(
0,
target = "row",
fontWeight = styleEqual(1, "bold")
)
rstudio DT页面提供了更多示例:http://rstudio.github.io/DT/010-style.html
或者,我认为您最好使用stargazer
包。
基础图看起来与您想要的结果非常相似。
stargazer::stargazer(df, type = "html", title = "Table 1")
这会让你开始,但请看这里有更多的灵活性:https://www.jakeruss.com/cheatsheets/stargazer/