Is there any way to generate multiple needs to validate using lapply

ORIGINAL

  ui <- fluidPage(
    checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
    selectInput('in2', 'Select a state', choices = state.name, selected = NULL),
    plotOutput('plot')
  )

  server <- function(input, output) {
    output$plot <- renderPlot({
      validate(
        need(input$in1, 'Check at least one letter!'),
        need(input$in2, 'Please choose a state.')
      )
      plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
    })
  }

  shinyApp(ui, server)

what I tried but failed

  req_para <- c("in1", "in2")




  ui <- fluidPage(
    checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
    selectInput('in2', 'Select a state', choices = state.name, selected = NULL),
    plotOutput('plot')
  )

  server <- function(input, output) {
    output$plot <- renderPlot({
      validate(
        unlist(lapply(req_para, function(i){
          print(eval(parse(text = paste0("!is.null(input$",i,")"))))

          need(parse(text = paste0("!is.null(input$",i,")")),paste0("please chosse ", i) )
        })
        ))
      plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
    })
  }

  shinyApp(ui, server)

Too much copy+pasting on your end. The first argument of need needs to be

eval(parse(text = paste0("input$",i)))

Or, even simpler

input[[i]]

here is my solution. welcome to better ones

req_para <- c("in1", "in2")




ui <- fluidPage(
  checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
  selectInput('in2', 'Select a state', choices = state.name, selected = NULL),
  plotOutput('plot')
)

server <- function(input, output) {
  output$plot <- renderPlot({
    temp_need = lapply(req_para, function(i){
      eval(parse(text = paste0("need(!is.null(input$",i,"),", "'", i, " is missing')")))
    })
    print(temp_need)
    temp_val <- "validate("
    
    for (i in 1: length(temp_need)) {
      if(!is.null(temp_need[[i]])){
        temp_val <- paste0(temp_val, "'", temp_need[[i]], "'", ",")
        
      }
    }
    temp_val <- substring(temp_val, 1, nchar(temp_val) - 1)
    
    temp_val <- paste0(temp_val, ")")
    
    eval(parse(text = temp_val))
    
    

    plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
    
    

  })
}

shinyApp(ui, server)

This is simpler

req_para <- c("in1", "in2")




ui <- fluidPage(
  checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
  selectInput('in2', 'Select a state', choices = state.name, selected = NULL),
  plotOutput('plot')
)

server <- function(input, output) {
  output$plot <- renderPlot({
    temp_need = lapply(req_para, function(i){
      eval(parse(text = paste0("need(input$",i,",", "'", i, " is missing')")))
    })

    do.call(validate, temp_need)
    

    plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
    
    

  })
}

shinyApp(ui, server)