Search code examples
rselectshinyconcatenationselectinput

combine two selectbox values in r shiny


I need to combine two select box values in R shiny. Select box 1 have year, select box 2 have month.

If user select 2018 and 06, I should get 2018-06 into a variable.

I tried paste(input$year,input$month,sep="-") But it is not working.


Solution

  • This should do, note that I changed from reative to reactiveValues as I think this should be more intutive for you where you can use the v$value which will contain what you want. I suggest you have a read over https://shiny.rstudio.com/articles/reactivity-overview.html so you have a better grasp of what is happening

    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)