【发布时间】:2022-01-18 17:13:50
【问题描述】:
在下面的 MWE 代码中,如下图所示,aggregate() 函数用于对数据框中的列求和。我希望用户能够通过单击单选按钮来选择要聚合的变量,Period_1 或 Period_2。目前以下仅针对Period_1进行编码。
如何修改每个aggregate() 函数中的$Period...,以反映用户单选按钮输入?所以在这个例子中,用户也可以按周期 2 聚合。
MWE 代码:
library(shiny)
data <- data.frame(Period_1=c("2020-01","2020-02","2020-03","2020-01","2020-02","2020-03"),
Period_2=c(1,2,3,3,1,2),
ColA=c(10,20,30,40,50,60),
ColB=c(15,25,35,45,55,65)
)
ui <-
fluidPage(
h3("Data table:"),
tableOutput("data"),
h3("Sum the data table columns:"),
radioButtons(
inputId = 'vetaDataView2',
label = NULL,
choices = c('By period 1','By period 2'),
selected = 'By period 1',
inline = TRUE
),
tableOutput("totals")
)
server <- function(input, output, session) {
sumColA <- aggregate(data$ColA~Period_1,data,sum)
sumColB <- aggregate(data$ColB~Period_1,data,sum)
totals <- as.data.frame(c(sumColA, sumColB[2]))
colnames(totals) <- c("Period_1","Sum Col A","Sum Col B")
output$data <- renderTable(data)
output$totals <- renderTable(totals)
}
shinyApp(ui, server)
【问题讨论】:
-
如果你只有两个选项,你可以使用
if/else在renderTable(或在renderTable内部调用的反应式内部)对计算进行硬编码。