Search code examples
rlubridate

Changing format from <chr> to <date> using lubridate changes the year


I am quite new to R, and I am trying to change a column where the date is formatted as data type <chr> and I would like it to be <date>.

I have tried the following chunk using Lubridate:

activity_level$ActivityDay <- as.Date(activity_level$ActivityDay, "%m/%d/%Y")

But it changes the date year from 2016 to 2020.

example:

4/12/2016 becomes 2020-04-12 instead of 2016-04-12

This occurs with all the dataframes, and I can't figure out why. I have not been able to find an answer that seems to work. My 'Y' is capitalized. The day and month remain correct.

I even tried:

activity_level$ActivityHour=as.POSIXlt(activity_level$ActivityHour, format="%m/%d/%Y")

but the same thing happened. All the dates in the data should be 2016, but all convert to 2020.

Any suggestions? Thanks!

 


Solution

  • Try this:

    activity_level <-
      activity_level |>
      mutate(
        ActivityDay = readr::parse_date(
          ActivityDay,
          format = "%m/%d/%Y"
        )
      )