【问题标题】:Formatting selectInput() to show character dates to the user格式化 selectInput() 以向用户显示字符日期
【发布时间】:2015-04-17 20:29:58
【问题描述】:

我目前正在构建一个闪亮的应用程序并尝试获取一组日期以将其作为字符串呈现给最终用户,同时在服务器端代码中调用时仍保持其日期格式。

这里可能有一个简单的解决方案,但不确定如何在 selectInput 下拉菜单中获取要格式化的日期。在我的实际用例中,使用日期滑块并不理想,因为日期不遵循共同的间隔。

下面的可重现示例:

# 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)

【问题讨论】:

  • 使用下面@cdeterman 的建议,当我使用list 或array 而不是data.frame 时,字符日期的UI 呈现将呈现为数组元素的名称的价值是巨大的。 my.list &lt;- setNames(test.dates, test.names)

标签: r shiny


【解决方案1】:

我相信你会发现在 Shiny 中传递 character 对象比传递 date 对象容易得多。我会简单地使用您的日期的直接character 值,并且只要您需要它们在您的后续分析中成为date 对象,就会显式转换为date 对象。下面提供了一个示例,其中下拉列表和表格都具有字符格式的日期。

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)

【讨论】:

  • 谢谢 - 这似乎容易多了。希望避免分析中的转换,因为它在阅读代码时会变得更加混乱,但没什么大不了的。我希望可能有一些与使用命名列表相关的解决方法,但我无法让它工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2013-07-29
相关资源
最近更新 更多