1

I wish to import my csv file into a data frame but the date in my csv file is in a non-standard format.

The date in the first column is in the following format:

08.09.2016

One of the arguments in my read.csv2 functions is to specify the classes and when I specify this column as a date I receive the following error upon execution:

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

I'm guessing it doesn't like converting the date from factor class to date class.

I've read a little about POSIXlt but I don't understand the details of the function.

Any ideas how to convert the class from factor to date??

TheGoat
  • 2,587
  • 3
  • 25
  • 58
  • 1
    Don't let the `colClasses` option of `read.csv2` do the conversion into date format. Instead, read the data without that option and convert to a date class afterwards by specifying the appropriate format. `df1 <- read.csv2(text="08.09.2016", header=FALSE); df1[,1] <- as.Date(df1[,1], format="%m.%d.%Y")` . – RHertel Aug 24 '16 at 21:53

1 Answers1

2

When you convert character to date, you need specify format if it is not standard. The error you got is the result of as.Date("08.09.2016"). But if you do as.Date("08.09.2016", format = "%m.%d.%Y"), it is fine.

I am not sure whether it is possible to pass format to read.csv2 for correct date formatting (maybe not). I would simply read in this date column as factor, then do as.Date(as.character(), format = "%m.%d.%Y") on this column myself.

Generally we use the following format "dd/mm/yy" how can I reorganise the date to that format?

Use format(, format = "%d/%m/%y").


A complete example:

format(as.Date("08.09.2016", format = "%m.%d.%Y"), format = "%d/%m/%y")
# [1] "09/08/16"
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • 1
    It is certainly possible to pass in your own format to a `read.csv2` - you have to make your own class first - http://stackoverflow.com/a/13022441/496803 – thelatemail Aug 24 '16 at 22:33