Given 是 R Shiny 应用程序中的一个复选框。显示的选项代表数值。如果选择了一个或多个选项,则应将数值相加得出最终结果。
如果复选框选项发生变化,结果应更新
以下示例:
library(shiny)
tbl <- cbind(letters[1:4], 1:4)
ui =fluidPage(
checkboxGroupInput("tbl","tbl:",tbl[,1]),
htmlOutput("tbl_sum")
)
server = function(input, output, session) {
tbl_1 <- reactive({
if (input$tbl == tbl[1,1]) {
tbl_txt <- tbl[1,2]
} else {0}
})
tbl_2 <- reactive({
if (input$tbl == tbl[2,1]) {
tbl_txt <- tbl[2,2]
} else {0}
})
tbl_3 <- reactive({
if (input$tbl == tbl[3,1]) {
tbl_txt <- tbl[3,2]
} else {0}
})
tbl_4 <- reactive({
if (input$tbl == tbl[4,1]) {
tbl_txt <- tbl[4,2]
} else {0}
})
tbl_sum <- reactive({ sum(tbl_1(), tbl_2(), tbl_3(), tbl_4()) })
output$tbl_sum <- renderText({
paste("<font color=red><b>", "here should appear a result", "</p>",
"for example: if 'b' and 'd' is checked the result should be", "</p>",
"<font color=black><font size=12><b>",
sum(as.numeric(tbl[2,2]) + as.numeric(tbl[4,2])))
})
}
runApp(list(ui = ui, server = server))
我既不确定“反应式”是最好的方法还是“观察”,也不确定数据结构(tbl)和书面函数(tbl_1)是否是最好的方法<-, tbl_2 <-, tbl_...) are the best ways to solve this task. Smarter solutions welcome!
您的方法有点复杂,即您可以使用一个
reactive
一次性获取所有选定的值。此外,您可以考虑使用允许将值存储为数字的数据框,而不是将类别和值存储在矩阵中。
library(shiny)
tbl <- data.frame(name = letters[1:4], value = 1:4)
ui <- fluidPage(
checkboxGroupInput(
"tbl", "tbl:", tbl$name
),
htmlOutput("tbl_sum")
)
server <- function(input, output, session) {
tbl_values <- reactive({
tbl[match(input$tbl, tbl$name), "value"]
})
output$tbl_sum <- renderText({
paste(
"<font color=red><b>", "here should appear a result", "</p>",
"for example: if 'b' and 'd' is checked the result should be", "</p>",
"<font color=black><font size=12><b>",
sum(tbl_values())
)
})
}
runApp(list(ui = ui, server = server))