在 readr 中使用语言环境的 date_format

Using locale's date_format in readr

如何正确设置语言环境的 date_format 以使用 readr 中的 cols()

而不是为每一列指定日期格式:

df <- read_csv2(my_file,
                col_types = cols(.default = '?',
                                 my_date = col_date(format = '%d.%m.%Y')))

我要指定一次。 cols() 的文档说:

col_date(format = "") [D]: with the locale's date_format.

所以我尝试了:

locale(date_format = '%d.%m.%Y')

df <- read_csv2(my_file,
                col_types = cols(.default = '?',
                                 my_date = 'D'))

但这会引发警告(收到 problems()):

expected: <chr> date in ISO8601
actual: <chr> 01.01.2000

您必须像这样将 locale(...) 作为参数传递给 read_csv2

library(readr)

data <- "date1; date2
01.01.2000; 30.01.2000
01.12.2000; 25.12.2000"

read_csv2(data, 
          col_types = "DD",
          locale = locale(date_format = '%d.%m.%Y'))