1

Having problems reading a European date format of date.month.year in R using readr, where date and month do not have leading zeros. E.g.

file:

1 date_of_birth
2 1.2.2016 

Tried (among others):

file <- read_csv2("file.csv",col_types = cols(
  date_of_birth=col_date("%d.%m.%Y")
  ))

results in date_of_birth : num 122016

Any help would be appreciated

talat
  • 68,970
  • 21
  • 126
  • 157
kporkka
  • 71
  • 1
  • 5
  • You would probably benefits from defining your own date format before calling read.csv2. See this post: [Specify custom Date format for colClasses argument in read.table/read.csv](http://stackoverflow.com/questions/13022299/specify-custom-date-format-for-colclasses-argument-in-read-table-read-csv). – Joseph Wood Feb 21 '17 at 14:51

1 Answers1

0

Is this what you're after?

> as.Date(gsub("\\.","\\/","1.2.2016"),"%d/%m/%Y")

[1] "2016-02-01"

Carl Boneri
  • 2,632
  • 1
  • 13
  • 15
  • 3
    `as.Date("1.2.2016","%d.%m.%Y")` should also work. – count Feb 21 '17 at 15:04
  • Thanks. This would work when the date variable would already be in that format in R. But when reading a csv file using readr::read_csv the variable is converted to a number and the periods are stripped (eg. "122016"). As there are no leading zeros this is difficult to convert to a date. So need to instruct read_csv to recognize the variable in the csv file as a date, which I cannot do. – kporkka Feb 21 '17 at 15:32
  • try data.table::fread and then colClass= 'character' and go from there – Carl Boneri Feb 21 '17 at 15:34
  • Thanks Carl, that was a simple solution. Using readr: file <- read_csv2("file.csv",col_types = cols( Date_of_birth=col_character() )) file$Date_of_birth <- as.Date(file$Date_of_birth, "%d.%m.%Y") – kporkka Feb 21 '17 at 16:20
  • so it worked for you? – Carl Boneri Feb 21 '17 at 16:21
  • Yes it did. Thanks! – kporkka Feb 21 '17 at 16:38
  • so...this is awkward... but you wanna check that accepted option? – Carl Boneri Feb 21 '17 at 16:43
  • I took your advise on reading the date as a string and the parsed that to a date. Just used dplyr::readr and read_csv instead of data.table::fread. – kporkka Feb 21 '17 at 16:52
  • okay so this answer is not accepted? – Carl Boneri Feb 21 '17 at 17:26