代码之家  ›  专栏  ›  技术社区  ›  www

参考更新后的UI输入ID,并计算其中的总和

  •  1
  • www  · 技术社区  · 7 年前

    ?insertUI . 我的问题是我不确定如何从更新的UI(在本例中是新的文本框)引用输入id。我目前的尝试无法计算总数。最终结果总是0。

    # Define UI
    ui <- fluidPage(
      actionButton("add", "Add UI"),
      actionButton("sum", "Sum"),
    
      # Report the output
      h4("The total from input"),
      textOutput("text")
    )
    
    # Server logic
    server <- function(input, output, session) {
      observeEvent(input$add, {
        insertUI(
          selector = "#add",
          where = "afterEnd",
          ui = textInput(paste0("txt", input$add),
                         "Insert some text")
        )
      })
    
      # Calculate the total from the text inputs
      output$text <- eventReactive(input$sum, {
        as.character(sum(as.numeric(unlist(mget(ls(pattern = "^txt"))))))
      })
    }
    
    # Complete app with UI and server components
    shinyApp(ui, server)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Nate xin ding    7 年前

    您可以使用特殊的变量 input

      output$text <- eventReactive(input$sum, {
        txt_inpt_names <- names(input)[grepl("^txt", names(input))]
    
        sum(sapply(txt_inpt_names, function(x) as.numeric(input[[x]])), na.rm = T)
      })
    

    Live demo

    值得注意的是,Shiny需要单个(一次一个)访问 输入 这就是为什么 sapply() 是必需的,而不仅仅是 input[[txt_inpt_names]] .