首页 > 解决方案 > Saving user input (Shiny app) to a global variable in R

问题描述

I want to save user selection as a character vector in my global environment for use in further analysis as input (my_choices dropdown) How can I save what was selected?

Example:

library("shiny")
library("shinyWidgets")

my_choices <- c(
  "2018Q1","2018Q2","2018Q3", "2018Q4", "2019Q1", "2019Q2")

ui <- fluidPage(

  pickerInput(
    inputId = "id",
    label = "SELECT PERIOD:",
    choices = my_choices,
    selected = NULL,
    multiple = TRUE, 
    options = list(
      `actions-box` = TRUE, size = 15, `selected-text-format` = "count > 3"
    ),
    choicesOpt = list(
      content = stringr::str_trunc(my_choices, width = 75)
    )
  ),
  verbatimTextOutput(outputId = "res")
)

server <- function(input, output, session) {
  output$res <- renderPrint(input$id)
}

shinyApp(ui = ui, server = server)

标签: rvariablesshinyglobal-variables

解决方案


尝试使用双头箭头进行全局赋值:

observe({
   your_global_variable <<- input$id
})

或使用以下assign()功能:

observe({
   assign(
      x = "your_global_variable", 
      value = input$id, 
      envir = .GlobalEnv
   )
})

推荐阅读