Test whether any input in a set of numbered input objects in R Shiny is empty

怎甘沉沦 提交于 2021-02-08 02:08:11

问题


Let's say I have created 10 selectInput dropdowns for a multi plot export and these selectInputs are called "xaxis_1", "xaxis_2", ..... , "xaxis_10"

for a single 1 I can write: if(!is.null(input$xaxis_1)) { .... do stuff } to stop it running export when the user hasn't entered any name, and presses submit, to avoid crashes.

A bit more general you can check this:

if(!is.null(input[[paste('xaxis', i, sep = '_')]])) { ...}

how can you write it elegantly so that 1 line of code checks whether ANY of the 1:10 input[[...]] is empty, i.e. NULL?

The nr of inputs depends on how many plots the user wants to export per file, so all is build with lapply(1:input$nrofplots, function(i) { .... } renderUI structure, and my if statement needs to have the same flexibility of 1:n

In a situation like below in the image, pressing Initiate export should give a sweetalert (got that covered) saying there is at least 1 value missing


回答1:


Here a snippet I used in the UI side to validate the user's inputs.

library(shiny)
library(shinyjs)

ui <- fluidPage(
 useShinyjs(),  # Set up shinyjs
 numericInput('axis1','Val 1',1),
 numericInput('axis2','Val 2',1),
 numericInput('axis3','Val 3',1),
 actionButton('Go','Plot')
)

server <- function(input, output, session) {
  #Try 1, space, AAA and check what shiny will return
  observe(print(input$axis1))
  observe({
    All_Inputs <- vapply(paste0('axis',1:3),
                                function(x){isTruthy(input[[x]])},
                                logical(1))
    All_InputsCP <- all(All_Inputs)
    shinyjs::toggleState(id="Go", condition = All_InputsCP) #This is to make the button Go able or disable according to condition All_InputsCP #
  })
}

shinyApp(ui, server)

I hope it helps.



来源:https://stackoverflow.com/questions/55206206/test-whether-any-input-in-a-set-of-numbered-input-objects-in-r-shiny-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!