我想显示一个按日期和时间值排序的值表,用户可以单击标题对表进行排序。
它应该通过 renderDataTable 在 Shiny/R 脚本上运行,但与我们在 RStudio 浏览数据帧中获得的行为相同。
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/