简体   繁体   中英

Formatting selectInput() to show character dates to the user

I am currently building a shiny app and trying to get a set of dates to render as character strings to the end user, while still keeping their date format when invoked in the server side code.

There might be a simple solution here, but unsure how to get the dates to format in the selectInput dropdown. In my actual use case, using a date slider isn't ideal as the dates do not follow a common interval.

Reproducible example below:

# setup
require(lubridate)
test.dates <- as.Date(c('2014-06-01', '2014-07-01', '2014-08-01',     
                        '2014-09-01', '2014-10-01', '2014-11-01',  
                        '2014-12-01', '2015-01-01','2015-02-01', 
                        '2015-03-01', '2015-04-01'))
test.names <- as.character(paste0(month(test.dates, label = T), ' ', 
                                  year(test.dates)))
test.df <- data.frame(date = test.dates)
row.names(test.df) <- test.names

# shiny
server <- function(input, output) {

   output$table <- renderTable(test.df)

}


ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("test", label = "DATE FORMAT TEST:", choices =   
                  test.df, selected = test.df[1,])
    ),
    mainPanel(tableOutput('table'))
  )
)

shinyApp(ui = ui, server = server)

I believe you will find it much easier to pass around character objects than date objects in Shiny. I would simply use the direct character values of your dates and whenever you need them to be date objects in your subsequent analysis explicitly convert to a date object. The following provides an example where both the dropdown and table have the character formatted dates.

require(lubridate)
myDates <- c('2014-06-01', '2014-07-01', '2014-08-01',     
             '2014-09-01', '2014-10-01', '2014-11-01',  
             '2014-12-01', '2015-01-01','2015-02-01', 
             '2015-03-01', '2015-04-01')
test.names <- as.character(paste0(lubridate::month(test.dates, label=TRUE), ' ', 
                                  year(test.dates)))
test.df <- data.frame(date = myDates)
row.names(test.df) <- test.names

# shiny
server <- function(input, output) {

    output$table <- renderTable(test.df)

}


ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectInput("test", label = "DATE FORMAT TEST:", choices =   
                            myDates, selected = myDates[1])
        ),
        mainPanel(tableOutput('table'))
    )
)

shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM