我有一个闪亮的应用程序,可以运行,我想将功能放入模块中以清理 app.R 脚本,使其更易于其他人阅读。
我一直在尝试转换与成本相关的代码块。下面是一个可重现的示例。我注释掉的代码有效,但正如您所看到的,我想为其编写一个函数,这样更容易阅读。正如目前注释掉的代码一样,它将运行并且不会产生任何错误,但不会更新 Cost1、Cost2 或 Cost3 的成本。我搜索了这里几乎所有其他问题,包括 link1、link2、link3、link4 和 link5,但我不能为我工作。
library(shiny)
ui <- fluidPage(
fluidRow(
column(2, actionButton("UpdateButton1", "UpdateButton1")),
column(2, actionButton("UpdateButton2", "UpdateButton2")),
column(2, actionButton("UpdateButton3", "UpdateButton3")),
),
fluidRow(
column(2,
numericInput("Cost1", "Cost 1", value = 10, min = 0),
numericInput("Cost2", "Cost 2", value = 20, min = 0),
numericInput("Cost3", "Cost 3", value = 30, min = 0)
)
)
)
server <- function(input, output, session) {
#
# observeEvent(input$UpdateButton1, {
# updateNumericInput(inputId = "Cost1", value = 100)
# updateNumericInput(inputId = "Cost2", value = 100)
# updateNumericInput(inputId = "Cost3", value = 100)
#
# })
#
# observeEvent(input$UpdateButton2, {
# updateNumericInput(inputId = "Cost1", value = 200)
# updateNumericInput(inputId = "Cost2", value = 200)
# updateNumericInput(inputId = "Cost3", value = 200)
#
# })
#
# observeEvent(input$UpdateButton3, {
# updateNumericInput(inputId = "Cost1", value = 300)
# updateNumericInput(inputId = "Cost2", value = 300)
# updateNumericInput(inputId = "Cost3", value = 300)
# })
#
# }
###The above works but I want to make it cleaner because I have a lot more costs so I wrote a function but it doesn't work:
update_costs_button1 <- function(id, Cost1, Cost2, Cost3){
moduleServer(id, function(input, output, session) {
updateNumericInput(inputId = Cost1, value = 100)
updateNumericInput(inputId = Cost2, value = 100)
updateNumericInput(inputId = Cost3, value = 100)
})
}
observeEvent(input$UpdateButton1, {
update_costs_button1("id1", "Cost1", "Cost2", "Cost3")
})
}
shinyApp(ui, server)
添加
session
就可以了。 试试这个
library(shiny)
ui <- fluidPage(
fluidRow(
column(2, actionButton("UpdateButton1", "UpdateButton1")),
column(2, actionButton("UpdateButton2", "UpdateButton2")),
column(2, actionButton("UpdateButton3", "UpdateButton3")),
),
fluidRow(
column(2,
numericInput("Cost1", "Cost 1", value = 10, min = 0),
numericInput("Cost2", "Cost 2", value = 20, min = 0),
numericInput("Cost3", "Cost 3", value = 30, min = 0)
)
)
)
update_costs_button1 <- function(id, mysession, Cost1, Cost2, Cost3){
moduleServer(id, function(input, output, session) {
updateNumericInput(mysession, inputId = Cost1, value = 100)
updateNumericInput(mysession, inputId = Cost2, value = 200)
updateNumericInput(mysession, inputId = Cost3, value = 300)
})
}
server <- function(input, output, session) {
observeEvent(input$UpdateButton1, {
update_costs_button1("id1", session, "Cost1", "Cost2", "Cost3")
})
}
shinyApp(ui, server)