是否可以在 R Shiny“数据表”代码中格式化日期?

问题描述 投票:0回答:1

我想根据所选语言在 DT::datatable 中渲染表格时更改日期格式。假设对于“EN”,格式应为“yyyy-mm-dd”,对于 FR,格式应为“dd-mm-yyyy”。

这是代码片段的草图

library(DT)
library(data.table)

language <- "en"

df <- data.table(
  date = c("2023-11-09", "2023-11-10", "2023-11-11"),
  value = c(1, 2, 3))

# The format of "date" column should fit selected language
datatable(df) %>% formatDate(language)

欢迎任何关于如何以与“formatPercentage”或“formatCurrency”相同的方式进行操作的想法,我们将不胜感激。

r date dt
1个回答
0
投票

我认为您需要根据查找表和您选择的国家/地区标识符编写自己的函数。

对于国家/地区代码这些(alpha-2 或 alpha-3),此 会派上用场。使用此表的想法以及大多数日期重新格式化技术是从@Maël 的answer 借来的。作为起点,我将这些想法包装在一个接受数据帧的函数中。

# function v0.0.1
formatDate <- \(dt, language) {
  stopifnot(nchar(language) %in% c(2L, 3L))
  stopifnot(is.data.frame(dt))
  # stopifnot(data.table::is.data.table(dt))
  if(!("date" %in% colnames(dt))) stop("Date column `date` is missing.")
  
  # if(is.character(dt$date)) dt[, date := as.Date(x = date, format = "%Y-%m-%d")]
  if(is.character(dt$date)) dt$date <- as.Date(x = dt$date, format = "%Y-%m-%d")
  
  lookup <- read.csv("https://gist.githubusercontent.com/mlconnor/1887156/raw/014a026f00d0a0a1f5646a91780d26a90781a169/country_date_formats.csv")
  
  lookup$Date.Format <- 
    stringr::str_replace_all(string = lookup$Date.Format, 
                             pattern = c("yyyy" = "%Y", "MM" = "%m",
                                         "(?<!M|%)M(?!M)" = "%m", "dd" = "%d",
                                         "M" = "%M", "2555" = "%Y",
                                         "(?<!d|%)d(?!d)" = "%a"))

  if(nchar(language) == 2L) {
    stopifnot(language %in% lookup$ISO639.2.Country.Code)
    f <- lookup[lookup$ISO639.2.Country.Code == language, "Date.Format"]
  } else {
    stopifnot(language %in% lookup$ISO.3166.Country.Code)
    f <- lookup[lookup$ISO.3166.Country.Code == language, "Date.Format"]
    
  }
  # dt[, date := format(x = date, format = f)]
  dt$date <- format(x = dt$date, format = f)
  dt
}

例如:

> df |> formatDate(language = "US") |> head()
         date value
1 11/Thu/2023     1
2 11/Fri/2023     2
3 11/Sat/2023     3
> df |> formatDate(language = "DEU") |> head()
        date value
1 09.11.2023     1
2 10.11.2023     2
3 11.11.2023     3
> df |> formatDate(language = "FR") |> head()
        date value
1 09/11/2023     1
2 10/11/2023     2
3 11/11/2023     3
> df |> formatDate(language = "ABC") |> head()
Error in formatDate(df, language = "ABC") : 
  language %in% lookup$ISO.3166.Country.Code is not TRUE

接受

data.table
类对象的版本只能运行一次(参见以
#
开头的行)。每次运行后都需要重新启动
R
会话才能获得与
NA
不同的结果。我是
{data.table}
的新手,还没有发现这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.