Export all user inputs in a Shiny app to file and load them later

前端 未结 3 1738
臣服心动
臣服心动 2020-12-15 13:39

My Shiny app has several inputs which are used to define several parameters of a generated plot. It\'s very likely that the user will spend some minutes going through all po

3条回答
  •  太阳男子
    2020-12-15 14:24

    If you look at the code of the shiny input update functions, they end by session$sendInputMessage(inputId, message). message is a list of attributes that need to be changed in the input, for ex, for a checkbox input: message <- dropNulls(list(label = label, value = value))

    Since most of the input have the value attribute, you can just use the session$sendInputMessage function directly on all of them without the try.

    Here's an example, I created dummy_data to update all the inputs when you click on the button, the structure should be similar to what you export:

    ui.R

    library(shiny)
    shinyUI(fluidPage(
      textInput("control_label",
                "This controls some of the labels:",
                "LABEL TEXT"),
      numericInput("inNumber", "Number input:",
                   min = 1, max = 20, value = 5, step = 0.5),
      radioButtons("inRadio", "Radio buttons:",
                   c("label 1" = "option1",
                     "label 2" = "option2",
                     "label 3" = "option3")),
      actionButton("update_data", "Update")
    
      ))
    

    server.R

    library(shiny)
    
    dummy_data <- c("inRadio=option2","inNumber=10","control_label=Updated TEXT" )
    
    shinyServer(function(input, output,session) {
      observeEvent(input$update_data,{    
        out <- lapply(dummy_data, function(l) unlist(strsplit(l, "="))) 
       for (inpt in out) {
         session$sendInputMessage(inpt[1], list(value=inpt[2]))
        }
       })
    
    })
    

    All the update functions also preformat the value before calling session$sendInputMessage. I haven't tried all possible inputs but at least for these 3 you can pass a string to the function to change the numericInput and it still works fine.

    If this is an issue for some of your inputs, you might want to save reactiveValuesToList(input) using save, and when you want to update your inputs, use load and run the list in the for loop (you'll have to adapt it to a named list).

提交回复
热议问题