1

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!!

Sotos
  • 51,121
  • 6
  • 32
  • 66
hagewhy
  • 79
  • 1
  • 1
  • 6

1 Answers1

2

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)
maRtin
  • 6,336
  • 11
  • 43
  • 66
  • 1
    wow it works! thanks so much :) I am very new to R. just wondering why format="%Y/%m/%d" can't work? R will require the date to be formatted in this order: ? – hagewhy May 05 '16 at 08:25
  • @hagewhy You applied the `as.Date()` function to a string (you enclosed `SP$Date.Sold` in "") and not to the column itself. Plus the date format has to match the actual format from your column. If my answer was helpful, please mark it as accepted. – maRtin May 05 '16 at 08:27