Converting chr to Date

I am trying to convert a date column which is chr and is like

1/2/2019 or m/d/y

So I tried this code

as.Date(supsale$Date,format = %y-%m-%d)

But it just comes back with

Error: unexpected SPECIAL in "as.Date(supsale$Date, format = %y-%"

This is my dataset - https://www.kaggle.com/aungpyaeap/supermarket-sales

What am I doing wrong?

You just need to specify the correct format within as.Date():

as.Date("1/2/2019", "%m/%d/%Y")

You've currently told it to look for dashes (-) and you're feeding it slashes (/) - I think that's what''s causing that error message.

1 Like

Thanks for your reply.

But I am still getting the same error message

Error: unexpected SPECIAL in "as.Date(3/12/2019, %m/%"

Make sure you use keep the quotes!

as.Date("1/20/2019",format = "%m/%d/%Y")

works, whereas

as.Date("1/20/2019",format = %m/%d/%Y)

will result in the error message you're getting.

Hi Darya,

Thank you, it worked but now all my data in the date column has become NA, instead of giving me a date format?

Would you happen to know what Ive done wrong?

It's hard for me to help without a reprex (reproducible example). To get one from your dataset, I recommend doing the following:

  1. Install the datapasta library
install.packages("datapasta")
  1. Do the same thing with your data frame as is done in the mini-video under: Scenario 2: From R object to tibble with dpasta() heading here: https://reprex.tidyverse.org/articles/articles/datapasta-reprex.html

  2. Paste the output of that command below so I can re-create your object, and that might enable me to help.

Thank you Darya,

I will try my best as I am very new to R and even have trouble understanding packages.

The lubridate package has convenient functions to parse date strings.

suppressPackageStartupMessages({library(lubridate)})

date1 <- "1/2/19"
date2 <- "2019-01-02"
date3 <- "2/1/19"
date4 <- "1-2-2019"

dmy(date1)
#> [1] "2019-02-01"
ymd(date2)
#> [1] "2019-01-02"
dmy(date3)
#> [1] "2019-01-02"
dmy(date4)
#> [1] "2019-02-01"

class(dmy(date4))
#> [1] "Date"

Created on 2020-09-25 by the reprex package (v0.3.0.9001)

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.