【问题标题】:Extracting Elements from Dynamic UI in R Shiny从 R Shiny 中的动态 UI 中提取元素
【发布时间】:2019-06-26 17:50:48
【问题描述】:

我有多个动态文本元素。元素的数量由下拉菜单决定。我想将每个动态文本元素组合到一个列表中,但遇到了困难。

我尝试创建一个单独的反应对象来组合项目。

server <-  function(input,output) {

  #define number of names and dynamic names
  output$input_ui1<- renderUI({
    num<- as.integer(input$num)
    lapply(1:num,
           function(i) {
             textInput(inputId = paste0("name",i ),
                       label= paste0("Name",i),
                       value= "enter name")

           })
  })

  #Names into list 
  names_list<-NULL  
  reactive({  
    for (i in 1:input$num ) {
      name<- input[[paste0("name",i)]]
      names_list<-c(names_list, name)
    }
  })


  #access first item of  list of names    
  output$test_text<-reactive({ 
    (names_list[1])  
  })

  #access first name    
  output$test_text2<-reactive({ 
    (input[["name1"]])  
  })



}


ui<- fluidPage(sidebarLayout(
  sidebarPanel(
    selectInput("num","select number of names",choices= seq(1, 10, 1)),
    uiOutput("input_ui1"),
    dateRangeInput("daterange1", "Date range:", start = "2001-01-01", end = "2010-12-31"),
    uiOutput("test_text"),
    uiOutput("test_text2")
  ),
  mainPanel()
))

shinyApp(ui=ui, server=server)

我的用户界面“test_test”和“test_test2”中有两个测试文本。我的期望是两者都应该显示相同的内容,但只有第二个显示的是预期的名字。

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    您对reactives 的使用不正确。如需更多信息,请参阅tutorial

    原码

    #Names into list 
    names_list<-NULL  
    reactive({  
      for (i in 1:input$num ) {
        name<- input[[paste0("name",i)]]
        names_list<-c(names_list, name)
      }
    })
    

    会发生什么:

    1. 您将names_list 定义为NULL
    2. 您定义了一个reactive,但它没有分配给任何对象,因此您无法访问它。 names_list 只是一个非反应对象,其值为NULL

    这部分真的很奇怪:

    #access first item of  list of names    
    output$test_text<-reactive({ 
      (names_list[1])  
    })
    

    test_textuiOutput,所以你应该使用renderUI

    替换代码:

    将反应式分配给names_list,然后通过names_list()访问它

    # Names into list 
    names_list <- reactive({  
      lapply(1:input$num, function(i) {
        input[[paste0("name",i)]]
      })
    })
    
    #access first item of  list of names    
    output$test_text <- renderUI( {
      names_list()[[1]]
    })
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2020-10-14
      • 2021-03-06
      相关资源
      最近更新 更多