0

I'm building a shiny app that interacts with a library I've built. Functions in that library have a bunch of optional arguments. The functions are written so that they can easily handle cases where missing(argument) == TRUE.

Shiny's input functions allow one to set the default value of the input if the user doesn't specify it themselves. Is it possible to set the default value to be missing (i.e., nonexistent)?

For example, this is how to set the default value to NULL, but that isn't what I want.

textInput("argument", label = "Set this optional argument",
          value = NULL)

EDIT: In all likelihood, I should just change my functions to have a default value of NULL, rather than using the missing function from base to set defaults. Nonetheless, I'm still curious if it's possible to set a default value to be nonexistent.

John J.
  • 1,450
  • 1
  • 13
  • 28
  • So, the issue is that if `input$argument` has a value, you call some function `f(value=input$argument)`, but if nothing is selected, you call `f()` with `value` receiving the default value? This is a more general problem with R optional values and I've seen a few different ways around it, none of which is fully satisfactory: – divibisan Mar 04 '19 at 16:30
  • This provides one option: https://stackoverflow.com/questions/32765153/make-conditional-argument-call-to-function-with-possibly-empty-argument?noredirect=1&lq=1 While this suggests using `missing`, rather than the default method for optional arguments, in your function which would give you more flexibility: https://stackoverflow.com/questions/28370249/correct-way-to-specifiy-optional-arguments-in-r-functions?noredirect=1&lq=1 – divibisan Mar 04 '19 at 16:30
  • @divibisan that's basically it, I've written my functions so that `if(missing(argument))`, then I set the default value to some function-specific value. – John J. Mar 04 '19 at 16:35

1 Answers1

1

The trick is to use do.call with a parameter list in which you put all your args for your function. Then you filter this list to filter out "missing" values. For a parameter in a textInput this could be an empty string (. == "") or any other criterion upon which you decide that this is a "missing" input.

f <- function(y, x) if (missing(x)) "is missing" else "present"

ui <- fluidPage(textInput("ti", "Set Arg:"), 
                verbatimTextOutput("out"))

server <- function(input, output) {
  output$out <- renderPrint({
     ## put all your potential args (optional and non optional) in a list 
     args <- list(y = 1, x = input$ti)
     ## Filter out NULL values
     ## define Filter fun which returns TRUE if you consider the value valid
     is_valid <- function(.) !is.null(.) && . != ""
     ## Filter out non valid args
     args <- Filter(is_valid, args)
     ## Use do.call to run your fun (non valid args are not set)
     list(inp = input$ti,
          out = do.call(f, args))
  })
}

shinyApp(ui, server)
thothal
  • 16,690
  • 3
  • 36
  • 71