convert string data.frame to Date

6.1k Views Asked by At

I am wondering why this error occurs. I would like to convert this using brackets as I am making sequential conversions in a loop. And because I just want to be able to do it and understand what is happening.

head(clean.deposit.rates)
       Date
1 1/31/1983
2 2/28/1983
3 3/31/1983
4 4/30/1983
5 5/31/1983
6 6/30/1983

class(clean.deposit.rates)
[1] "data.frame"

class(as.Date(clean.deposit.rates[[1]], "%m/%d/%Y"))
[1] "Date"



    class(as.Date(clean.deposit.rates$Date, "%m/%d/%Y"))
[1] "Date"



 as.Date(clean.deposit.rates["Date"], "%m/%d/%Y")
    Error in as.Date.default(clean.deposit.rates["Date"], "%m/%d/%Y") : 
      do not know how to convert 'clean.deposit.rates["Date"]' to class “Date”
2

There are 2 best solutions below

0
On BEST ANSWER

You need to use two [ brackets. With one, the column remains as a data frame. With two, it becomes an atomic vector which can properly be passed to the correct as.Date method

as.Date(df["Date"], "%m/%d/%Y")
# Error in as.Date.default(df["Date"], "%m/%d/%Y") : 
#   do not know how to convert 'df["Date"]' to class “Date”

Since df["Date"] is class data.frame, the x argument uses as.Date.default because there is no as.Date.data.frame method. The error is triggered because x is FALSE for all the if statements and continues through as.Date.default to the line

stop(gettextf("do not know how to convert '%s' to class %s", 
     deparse(substitute(x)), dQuote("Date")), domain = NA) 

Using df[["Date"]], the column becomes a vector and is passed to either as.Date.character or as.Date.factor depending on the class of the vector, and the desired result is returned.

as.Date(df[["Date"]], "%m/%d/%Y")
# [1] "1983-01-31" "1983-02-28" "1983-03-31" "1983-04-30" "1983-05-31"
# [6] "1983-06-30"
1
On

If you want to do this for multiple columns in a single data frame, then use the lapply function. Something like:

colNames <- c('StartDate','EndDate')

mydf[colNames] <- lapply( mydf[colNames], as.Date, "%m/%d/%Y" )