David_12 David_12 - 10 days ago 6
R Question

Change data type from Factors to Date in R

I'm pulling out data from a sql, one of the fields are date type but from some reason R recognize this data as Factors.

this is how R recognize this field:

$ RegDate : Factor w/ 666 levels "2015-02-02","2015-02-03",..: 1 1 1 1 1 1 1 1 2 2 ...


I tried several ways to change the type like

as.Date(RawDate$RegDate, format = "%m/%d/%Y %H:%M:%S")
- didn't change anything

as.POSIXct(x,format="%Y-%m-%d)
- when I used this kind of funcation i got all NAs

Any idea how should I do this?
Thanks

Answer

This is a format issue. The 'RegDate' is already in the same format as Date class. So, what we need is just wrapping with as.Date

RawDate$RegDate <- as.Date(RawDate$RegDate)

The reason why it got read as a factor variable is because of the default option stringsAsFactors=TRUE for character elements in read.csv/read.table or from whatever function you used. One way, is to specify the colClasses argument in read.csv/read.table