David_12 David_12 - 1 year ago 80
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

- when I used this kind of funcation i got all NAs

Any idea how should I do this?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download