r - 如何根据 Shiny R 脚本的格式为 "%d/%m/%Y %H:%M:%S"的时间戳列对数据帧进行排序

标签 r sorting datetime shiny

我想显示一个按日期和时间值排序的值表,用户可以单击标题对表进行排序。

它应该通过 renderDataTable 在 Shiny/R 脚本上运行,但与我们在 RStudio 浏览数据帧中获得的行为相同。

data frame

d1 是原始格式,它类似于字符串,所以我尝试将 d2 作为 POSIXct 版本,它可以工作,但我没有解决仅显示 d1 的问题。

myTS <- data.frame(d1=c("01/01/2016 10:00:45", 
                           "01/02/2016 10:00:45",
                           "01/03/2016 10:00:45",
                           "01/04/2016 10:00:45",
                           "10/01/2016 15:00:45",
                           "15/01/2016 15:00:45")) 
                            myTS$d2 <- as.POSIXct(strptime(myTS$d1, "%d/%m/%Y %H:%M:%S"))

如何仅显示格式为“%d/%m/%Y %H:%M:%S”的 d1,但在转换为 POSIXct 时正确排序?

谢谢

若昂

最佳答案

好吧,这不是最简单的方法,但如果您确实想要此功能,那么就在这里:

无法修改 DT 对其条目进行排序的方式。但我们可以改变它格式化输出的方式。那么为什么不将日期时间存储为数值(排序不会有问题)并仅将其显示为日期值。

有一个标准格式化程序(formatDate())可以轻松(但丑陋)进行日期时间转换。但如果您想要特定的东西,则必须使用 JavaScript 对其进行格式化(如果您已经有一个可以使用的模板,这并不难)。

this link ,第 4.5 章您将找到一些有关使用 rowCallback 的格式化函数的一般信息。我使用了这个以及一些使用 JavaScript 进行的冗长的手动日期时间格式化。

library(DT)
library(shiny)

ui <- shinyUI(fluidPage(
  DT::dataTableOutput("table")
))

server <- function(input, output){
  myTS <- data.frame(d1=c("01/01/2016 10:00:45", 
                           "01/02/2016 10:00:45",
                           "01/03/2016 10:00:45",
                           "01/04/2016 10:00:45",
                           "10/01/2016 15:00:45",
                           "15/01/2016 15:00:45",
                           "16/04/2016 01:00:00")) 
  myTS$d2 <- as.POSIXct(strptime(myTS$d1, "%d/%m/%Y %H:%M:%S"))
  myTS$d3 <- as.integer(myTS$d2)

  output$table <- DT::renderDataTable({
    datatable(myTS, options = list(rowCallback = JS("
      function(row, data){
      /* Create a Date. Note: R stores time in seconds, JavaScript in milliseconds. data[3] marks the third column. + converts to numeric. */ 
      var date = new Date(+data[3]*1000);
      /* I found this pad function somewhere on StackOverflow. */
      function pad(n) {return n < 10 ? '0'+n : n;}
      /* If you'd like some other format, change it here. */
      var dateString = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear() + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
      $('td:eq(3)', row).html(dateString);
    }")))
  })
}

shinyApp(ui, server)

如果您有疑问,请通知我。 玩得开心!

关于r - 如何根据 Shiny R 脚本的格式为 "%d/%m/%Y %H:%M:%S"的时间戳列对数据帧进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36635045/

相关文章:

r - 将丢失的时间行插入到数据框中

java - 从java中的List中获取元素的范围

php - 以程序方式评估 DateTime::diff 对象

MYSQL 选择日期早于日期时间的行

R - 将 float 转换为日期

r - 分解日期范围,行为 R

r - 加快R中大型数据帧的处理

python - 仅当元组中的数字相等时,如何根据字母顺序排列此列表中的元组?

r - 分组摘要/子集 dplyr

java - 如何生成每个随机数之间具有特定间隔的随机数