Home > Mobile >  Using locale's date_format in readr
Using locale's date_format in readr

Time:03-07

How do I correctly set locale's date_format to work with cols() from readr?

Instead of specifying the date format for every column:

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

I want to specify it once. cols()'s documentation says:

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

so I tried:

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

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

But this throws the warning (received with problems()):

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

CodePudding user response:

You have to pass the locale(...) as a parameter to read_csv2 like this:

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'))
  • Related