简体   繁体   中英

R Shiny using a list of input names into observeEvent

I generate an UI with a variable number of inputs (with variable names). How can I use the names of these inputs as a one-time argument into observe() or observeEvent() ?

library(shiny)
library(plotly)
df1<-data.frame(a=rnorm(100),b=rnorm(100),c=rnorm(100),ID1=c("A","B"),ID2=(c("A","B","C","D")))

# Define UI for application that draws a histogram
ui<-fluidPage(
  fluidRow(
    sidebarPanel(
      selectInput("select1","Select the ID",choices = colnames(df1[,4:5]),multiple = FALSE),
      # actionButton("act1","Go"),
      uiOutput("myui"),
      # keep track of the last selection on all selectInput created dynamically
      
    ),
    mainPanel(
      #tableOutput("table1"),
      plotlyOutput("plot.3d",height = "1000px")
    )
  )
)

# Define server logic required to draw a histogram
server<-function(input,output){
  rv <- reactiveValues(mygroup = 0, uitaglist = list(), uilabels = list())
  
  observeEvent(input$select1, {
    newgroup <- unique(df1[,input$select1])
    rv$mygroup <- newgroup
    
    # ui tags
    rv$uitaglist <- list()
    for(i in 1:length(rv$mygroup)){
      rv$uitaglist[[i]]<-colourpicker::colourInput(
        inputId = paste0("ColorID",i),
        label = rv$mygroup[i])
      rv$uilabels[[i]] <- paste0("ColorID",i)
    }
    # print(rv$uilabels)
    # print(names(input))
  })
  
  output$myui <- renderUI({
    rv$uitaglist
  })
  
  # observeEvent(input[rv$uilabels], { #Error in [: Can't index reactivevalues with `[`
  #   print(input[[rv$uilabels[[1]]]])
  # })
   
  # observeEvent(rv$uilabels, { # no effect
  #   print(input[[rv$uilabels[[1]]]])
  # })

  # observe({ # no effect
  #   rv$uilabels
  #   print(rv$uilabels)
  # })
  
} # end server


# Run the application 
shinyApp(ui = ui, server = server)

Turns out this could be done by:

  observe({
    rv$input_subset <- lapply(rv$uilabels, function(x) input[[x]])
    print(rv$input_subset)
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM