首页 > 解决方案 > 在 r shiny 中组合两个选择框值

问题描述

我需要在 R Shiny 中组合两个选择框值。选择框 1 有年份,选择框 2 有月份。

如果用户选择 2018 和 06,我应该将 2018-06 放入变量中。

我试过paste(input$year,input$month,sep="-")但它不起作用。

标签: rselectshinyconcatenationselectinput

解决方案


这应该可以,请注意我从 更改reativereactiveValues因为我认为这对您来说应该更直观,您可以使用v$valuewhich 将包含您想要的内容。我建议您阅读https://shiny.rstudio.com/articles/reactivity-overview.html以便您更好地了解正在发生的事情

library(shiny)

ui <- fluidPage(
  textOutput("value"),
  selectInput("year","year",choices = c(2017,2018),selected = 1),
  selectInput("month","month",choices = c(1:12),selected = 1)

)

server <- function( session,input, output) {

  v <- reactiveValues(value=NULL)

  observe({
    year <- input$year
    month <- input$month
    if(nchar(month)==1){
      month <- paste0("0",month)
    }
    v$value <- paste(year,month,sep="-")
  })

  output$value <- renderText({
    v$value
  })
}

shinyApp(ui, server)

推荐阅读