Date format - problems with conversion

Hi,
I have a column with date in this form:

01 Jan 10
02 Jan 10
03 Jan 10

I would like to change the date format, so R studio can recognize this as a date format.

I tried this: date$mydata <- format(as.Date(date$mydata), "%Y/%m/%d"). But I got an error message:
Error in date$mydata : $ operator is invalid for atomic vectors.

How can I fix it please?

It seems the object date is not a list or data frame. Perhaps you mean to use

mydata$date

If that does not fix the error, please post the output of

str(date)

or

str(mydata)

Also, the format argument of as.Date() represents the format of the input, so you want to use something like

as.Date("01 Jan 10", format="%d %b %y")

except you will have a variable where I have "01 Jan 10".

The code below should give you a new vector with the values in date converted to numeric dates.

dateNew <- as.Date(date, format="%d %b %y")

Here is a reproducible example with a small version of your date variable.

date <- factor(c("01 Jan 19", "02 Jan 19", "03 Jan 19"))
str(date)
#>  Factor w/ 3 levels "01 Jan 19","02 Jan 19",..: 1 2 3
dateNew <- as.Date(date, format = "%d %b %y")
str(dateNew)
#>  Date[1:3], format: "2019-01-01" "2019-01-02" "2019-01-03"
dateNew
#> [1] "2019-01-01" "2019-01-02" "2019-01-03"

Created on 2019-11-13 by the reprex package (v0.3.0.9000)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

Thanks a lot for your reply. I switched to mydata$date, however it still did not work.

The output of str(date) is:

Factor w/ 2191 levels "01 Apr 10","01 Apr 11",..: 25 25 97 169 385 817 817 961 1105 1105 ...

How can I fix it, please?