Shiny: Сохранить значения в соответствии с выбором переключателя? - PullRequest
1 голос
/ 31 марта 2020

Учитывая следующее блестящее приложение, я хочу щелкнуть переключатель и настроить входы и сохранить их в реактивные переменные. Моя цель - получить соответствующий ввод и сохранить его в переменной на основе выбора переключателя.

Вот что я сделал до сих пор:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  verbatimTextOutput("queryText"),
  sidebarLayout(
    sidebarPanel(
      radioButtons(
        inputId = "type",
        label = "Reminder Type",
        choices = c("Single Date Reminder" = "single",
                    "Multi Date Reminder" = "multi",
                    "From-To Reminder" = "from_to"),
        selected = "single", width = '100%'
      )
    ),
    mainPanel(
      conditionalPanel(
         condition = "input.type == 'single'",
        airDatepickerInput(
          inputId = "datetime",
          label = "Pick date and time:",
          timepicker = TRUE,
          clearButton = TRUE,
          update_on = "change"
        )
      ),
      conditionalPanel(
        condition = "input.type == 'multi'",
        airDatepickerInput(
          inputId = "multiple",
          label = "Select multiple dates:",
          placeholder = "You can pick 10 dates",
          multiple = 10, 
          timepicker = TRUE,
          clearButton = TRUE
        ),
      ),
      conditionalPanel(
        condition = "input.type == 'from_to'",
        airDatepickerInput(
          inputId = "range",
          label = "Select range of dates:",
          range = TRUE, 
          value = c(Sys.Date()-7, Sys.Date()),
          clearButton = TRUE
        ),
        airDatepickerInput(
          inputId = "range_time",
          label = "Pick Time:",
          timepicker = TRUE,
          onlyTimepicker = TRUE,
          clearButton = TRUE
        )
      )
    )
  ),
  tableOutput('show_inputs')
)

server <- function(input, output, session) {
  output$queryText <- renderText({
    query <- parseQueryString(session$clientData$url_search)
    paste("Reminder for ", query[['drug']], sep = "")
  })

  AllInputs <- reactive({
    x <- reactiveValuesToList(input)
    data.frame(
      names = names(x),
      values = unlist(x, use.names = FALSE)
    )
  })
  output$show_inputs <- renderTable({
    AllInputs()
  })
}

shinyApp(ui, server)

1 Ответ

1 голос
/ 01 апреля 2020

Я не очень знаком с airDatepickerInput, и я получил ошибку из вашего ввода range_time, поэтому я удалил его. В любом случае, вы, вероятно, захотите реактив (...) с некоторой логикой if-else c, чтобы упорядочить выбор пользователя. Вы можете попробовать это:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
    verbatimTextOutput("queryText"),
    sidebarLayout(
        sidebarPanel(
            radioButtons(
                inputId = "type",
                label = "Reminder Type",
                choices = c("Single Date Reminder" = "single",
                            "Multi Date Reminder" = "multi",
                            "From-To Reminder" = "from_to"),
                selected = "single", width = '100%'
            )
        ),
        mainPanel(
            conditionalPanel(
                condition = "input.type == 'single'",
                airDatepickerInput(
                    inputId = "datetime",
                    label = "Pick date and time:",
                    timepicker = TRUE,
                    clearButton = TRUE,
                    update_on = "change"
                )
            ),
            conditionalPanel(
                condition = "input.type == 'multi'",
                airDatepickerInput(
                    inputId = "multiple",
                    label = "Select multiple dates:",
                    placeholder = "You can pick 10 dates",
                    multiple = 10,
                    timepicker = TRUE,
                    clearButton = TRUE
                ),
            ),
            conditionalPanel(
                condition = "input.type == 'from_to'",
                airDatepickerInput(
                    inputId = "range",
                    label = "Select range of dates:",
                    range = TRUE,
                    value = c(Sys.Date()-7, Sys.Date()),
                    clearButton = TRUE,
                    timepicker = TRUE
                ),

            )
        )
    )
)

server <- function(input, output, session) {
    output$queryText <- renderText({
        query <- parseQueryString(session$clientData$url_search)
        paste("Reminder for ", query[['drug']], " on date(s): ", paste0(AllInputs(), collapse = "; "), sep = "")
    })

    AllInputs <- reactive({
        if(input$type == "single"){
            return(input$datetime)
        }
        if(input$type == "multi"){
            return(input$multiple)
        }
        if(input$type == "from_to"){
            return(input$range)
        }
    })
}

shinyApp(ui, server)

Вы также можете сохранить более надежный реактив, как показано ниже:

server <- function(input, output, session) {
    output$queryText <- renderText({
        query <- parseQueryString(session$clientData$url_search)
        paste("Reminder for ", query[['drug']], " on date(s): ", AllInputs()$pretty, sep = "")
    })

    AllInputs <- reactive({
        if(input$type == "single"){
            return(list("raw" = input$datetime,
                        "type" = "single",
                        "pretty" = input$datetime))
        }
        if(input$type == "multi"){
            return(list("raw" = input$multiple,
                        "type" = "multi",
                        "pretty" = paste0(input$multiple, collapse = "; ")))
        }
        if(input$type == "from_to"){
            return(list("raw" = input$range,
                        "type" = "range",
                        "pretty" = paste0(input$range[1], " to ", input$range[2])))
        }
    })
}
...