for loop有光泽的变量赋值

时间:2017-06-09 22:38:56

标签: r shiny

我有一大堆代码被重复20次,其中显示相同的信息,图表等,并且显示的数据集的数量取决于用户在闪亮中选择的输入字段数应用程序。而不是复制/粘贴此代码并从" Job1"更改输入名称。到" Job2"在第二个块中,我想引入一个for循环。我的问题是如何为顺序的闪亮输入进行变量赋值。我已经尝试过paste0来完成我想做的事,没有运气。

示例代码显示我尝试使用for循环来执行4次迭代的相同操作。我尝试做这项工作的部分是在ui顶部附近注释掉的。它现在的方式按预期工作,但你可以看到它不干净,非常乏味。此外,这在服务器端会是什么样子(我的尝试现在也被注释掉了)

      ui <- fluidPage(
      numericInput("num_selected", label = "Fields to Display", value = 0, min = 0, max = 4, step = 1),


      # for (i in 1:4 ) {
      #     conditionalPanel(
      #       condition = "input.num_selected >= i",
      #       textInput(paste0("Name", i), "Name"),
      #       textInput(paste0("Job", i), "Job")
      # )
      # }



    conditionalPanel(
      condition = "input.num_selected >= 1",
      textInput("Name1", "Name"),
      textInput("Job1", "Job")
    ),



    conditionalPanel(
      condition = "input.num_selected >= 2",
      textInput("Name2", "Name"),
      textInput("Job2", "Job")
    ),


    conditionalPanel(
      condition = "input.num_selected >= 3",
      textInput("Name3", "Name"),
      textInput("Job3", "Job")
    ),


    conditionalPanel(
      condition = "input.num_selected >= 4",
      textInput("Name4", "Name"),
      textInput("Job4", "Job")
    )
    )

    server<-function(input,output,session)
    {
      # for (i in 1:20 ) {
      # output$paste0("Name", i) <- ...
      # output$paste0("Job", i) <- ...
          # }
    }

    shinyApp(ui=ui, server=server)

1 个答案:

答案 0 :(得分:2)

您可以使用tagList()renderUI()

ui <- fluidPage(
  numericInput("num_selected", label = "Fields to Display", value = 0, min = 0, max = 10, step = 1),
  uiOutput("condPanels")
)

server<-function(input,output,session){

  output$condPanels <- renderUI({
    # if selected value = 0 dont create a condPanel,...
    if(!input$num_selected) return(NULL)
    tagList(
      lapply(1:input$num_selected, function(nr){
        conditionalPanel(
          condition = paste0("input.num_selected >= ", nr),
          textInput(paste0("Name", nr), "Name"),
          textInput(paste0("Job", nr), "Job")
        )
      })
    ) 
  })

}

shinyApp(ui=ui, server=server)