[R] How to Transform a Factor Variable into a Date

Paul Bernal paulbernal07 at gmail.com
Mon Jun 19 21:07:25 CEST 2017


Dear all,

Hope you are doing great. I have a .csv file that I read into R, the .csv
file consistss of two fields (TransitDate and CargoTons).

The TransitDate I formatted from Excel in the fashion mmm-yy (e.g.:
Apr-2013). However R does not recognize the field TransitDate as a date
field.

Here is the code:

library(lubridate)

Dataset <- read.table("U:/NEWCargoData.csv", header=TRUE, sep=",",
na.strings="NA", dec=".", strip.white=TRUE)

DatasetFrame <- data.frame(Dataset)

DatasetFrame$TransitDate <- as.Date(DatasetFrame$TransitDate, format =
"%b-%y")


Now, when I do DatasetFrame[1,1], the following happens:


> DatasetFrame[1,1]
[1] NA
>
> DatasetFrame[2,1]
[1] NA
>

Now when I do:

> Dataset[1,1] #this is the dataset as was read from my computer
[1] Jun-11
62 Levels: Apr-13 Apr-14 Apr-15 Apr-16 Apr-17 Aug-13 Aug-14 Aug-15 Aug-16
Dec-12 Dec-13 Dec-14 ... Sep-16
>

I am also attaching the .csv file for your reference. How can I do to get R
to convert TransitDate into an actual date  field? R is not recognizing it
as a date.

Any help will be greatly appreciated,

Best regards,

Paul


More information about the R-help mailing list