正在创建可重新反应的自定义渲染页脚值



我很难在reactable中呈现页脚列。我想在这里使用JS来访问客户端的过滤状态,由于我不太熟悉JS,我被卡住了。我想要的是:使用两列的汇总页脚值为第三列创建汇总页脚值。请参阅下面的示例。

library(shiny)
library(tidyverse)
data = tibble(article =c("a", "b", "c"), sales = c(12,34,16), margin = c(6,20,9)) %>%
mutate(profit = round(margin / sales * 100, digits = 2))
ui = fluidPage(

div(style = "margin-top: 50px; display: flex; justify-content: center;",
reactableOutput(outputId = "table"))

)
server = function(input, output, session){

output$table = renderReactable({
reactable(
data = data,
columns = list(
article = colDef(
footer = "..."),
sales = colDef(
format = colFormat(suffix = "€"),
footer = JS("function(colInfo) {
var total = 0
colInfo.data.forEach(function(row) {
total += row[colInfo.column.id]
})
return total.toFixed(2) + '€'}")),
margin = colDef(
format = colFormat(suffix = "€"),
footer = JS("function(colInfo) {
var total = 0
colInfo.data.forEach(function(row) {
total += row[colInfo.column.id]
})
return total.toFixed(2) + '€'}")),
profit = colDef(
format = colFormat(suffix = "%"),
footer = "35/62*100"
)
))
})

}
shinyApp(ui, server)

来自reactable开发者的解决方案

下面是一个页脚渲染函数的示例,该函数使用CCD_ 2。它类似于除了colInfo.data代替rows之外。

library(reactable)
library(dplyr)
set.seed(10)
data <- sample_n(MASS::Cars93[23:40, ], 30, replace = TRUE) %>%
mutate(Price = Price * 3, Units = sample(1:5, 30, replace = TRUE)) %>%
mutate(Avg.Price = Price / Units) %>%
select(Model, Manufacturer, Price, Units, Avg.Price)
reactable(
data,
groupBy = "Manufacturer",
columns = list(
Price = colDef(aggregate = "sum"),
Units = colDef(aggregate = "sum"),
Avg.Price = colDef(
# Calculate the aggregate Avg.Price as `sum(Price) / sum(Units)`
footer = JS("function(colInfo) {
let totalPrice = 0
let totalUnits = 0
colInfo.data.forEach(function(row) {
totalPrice += row['Price']
totalUnits += row['Units']
})
return (totalPrice / totalUnits).toFixed(2)
}")
)
)
)

最新更新