我有一個閃亮的應用程式,它使用 renderTable 從資料框串列中輸出表格。下面顯示了一個最小的示例。我希望輸出表有一些以科學計數法輸出的行,而其他行以百分比格式輸出。我該怎么做呢?
library(shiny)
# create dummy CSVs -------------------------------------------------------
DF1 <- data.frame(x = c(1.1, 2.1, 3.4), y = c(5.6, 4.2, 6.7))
DF2 <- data.frame(x = c(2.4, 6.7, 8.9), y = c(4.1, 6.3, 8.4))
DF3 <- data.frame(x = c(3.5, 9.5, 3.2), y = c(1.4, 4.5, 7.2))
DF4 <- data.frame(x = c(2.1, 7.4, 8.2), y = c(1.5, 7.2, 6.2))
mapply(
write.csv,
x = list(DF1, DF2, DF3, DF4),
file = list("DF1.csv", "DF2.csv", "DF3.csv", "DF4.csv"),
row.names = FALSE
)
# shiny app ---------------------------------------------------------------
ui <- fluidPage(sidebarLayout(
sidebarPanel(
fileInput(
"files",
"Choose File",
multiple = TRUE,
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".dp_txt",
".is_txt"
)
),
selectizeInput(
inputId = "selected_table",
label = "Table Selection",
choices = NULL,
selected = NULL,
multiple = FALSE
)
),
mainPanel(tableOutput("table"))
))
server <- function(input, output, session) {
observeEvent(input$files, {
freezeReactiveValue(input, "selected_table")
updateSelectizeInput(session,
inputId = "selected_table",
choices = input$files$name,
server = TRUE)
})
table_list <- reactive({
req(input$files)
setNames(lapply(input$files$datapath, function(x) {
fread(x)
}),
input$files$name)
})
output$table <- renderTable({
req(table_list(), input$selected_table)
table_list()[[input$selected_table]]
}, server = FALSE)
}
shinyApp(ui, server)
我知道我可以使用基本 Rformat()函式將行轉換為科學計數法,也可以使用label_percent()包scales中的 將行轉換為百分比格式。我還沒有找到在同一張表中混合這些格式更改的方法。
uj5u.com熱心網友回復:
可能有多種方法可以實作您想要的結果(并且可能比我下面的代碼更有效,它lapply用于回圈列并進行行的格式化。因為您沒有指定要格式化的行我如何格式化科學的第 1 行和百分比格式的第 2 到 3 行:
注意:我洗掉了所有檔案輸入內容以使 reprex 成為最小的可重現示例。
library(shiny)
DF1 <- data.frame(x = c(1.1, 2.1, 3.4), y = c(5.6, 4.2, 6.7))
DF2 <- data.frame(x = c(2.4, 6.7, 8.9), y = c(4.1, 6.3, 8.4))
DF3 <- data.frame(x = c(3.5, 9.5, 3.2), y = c(1.4, 4.5, 7.2))
DF4 <- data.frame(x = c(2.1, 7.4, 8.2), y = c(1.5, 7.2, 6.2))
ui <- fluidPage(sidebarLayout(
sidebarPanel(
selectInput("selected_table", "Select a table", paste0("DF", 1:4))
),
mainPanel(tableOutput("table"))
))
server <- function(input, output, session) {
table_list <- reactive({
setNames(list(DF1, DF2, DF3, DF4), paste0("DF", 1:4))
})
output$table <- renderTable({
req(table_list(), input$selected_table)
tbl <- table_list()[[input$selected_table]]
to_scientific <- 1
to_percent <- 2:3
lapply(tbl, function(x) {
xx <- x
xx[to_scientific] <- scales::scientific(x[to_scientific])
xx[to_percent] <- scales::percent(x[to_percent], scale = 1)
xx
})
}, server = FALSE)
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:8112

使用reprex v2.0.2創建于 2022-10-10
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513422.html
標籤:r闪亮的
上一篇:如何使用reactiveValues為特定的行和列設定最大值和最小值?
下一篇:JLinkXML依賴問題
