as.Date command in R returns NA

hagewhy picture hagewhy · May 5, 2016 · Viewed 10.5k times · Source

My date variable keeps returning a "NA" when i use the as.Date() command.

I have practically tried all the various ways, which include

(a) stating the origin argument; (b) setting the locale (c) converting the original variable into characters before reading in the csv file (read.csv("<file name>.csv", stringsAsFactors=FALSE) (d) stating the format in the as.Date argument (e) converting the original variable into numeric

I am reading a .csv file into R. The structure of the original variable is:

$ Date.Sold                : Factor w/ 30 levels "","01/10/2015",..: 1 1 1 1 1 

I have tried to convert the $Date.Sold field into a date variable, so that i can ultimately extract the Year from it. The command which i am using is:

SP$Date.Sold = as.Date("SP$Date.Sold",format="%Y/%m/%d", origin="1899-12-30")

Help!!

Answer

maRtin picture maRtin · May 5, 2016

Try this:

SP$Date.Sold = as.Date(SP$Date.Sold,format="%d/%m/%Y")

but if you just want to extract the year, you can do the following:

SP$Date.Sold = substr(SP$Date.Sold,7,11)