dates in R with lubridate

Hi R com.
i have a df with a date column like this:
image

When i try something like:

date format

df1 <- ymd(df$Date)

to change the dataformat i get all NA

What i need is a date column in the format d-m-Y and Y-m-d

Thx!

Hello,

I created just two dates with your specification above, so just apply it to your data.frame:

dates <- c('07312021','08122021')
# Y-m-d format (standard R Date format)
dates |>
  as.Date(format = '%m%d%Y')
#> [1] "2021-07-31" "2021-08-12"
# d-m-Y format
dates |>
  as.Date(format = '%m%d%Y') |>
  format('%d-%m-%Y')
#> [1] "31-07-2021" "12-08-2021"

Created on 2022-08-24 by the reprex package (v2.0.1)

You actually don't need lubridate in this case, if you want to display the dates in the format "%Y-%m-%d" or "%d-%m-%Y"respectively (as you've mentioned). lubridate would just create regular dates (Ymd) out of your "not regular" dates.

Kind regards

Edit: But note that the non standard formatted Date is a chr vector, but the regular one is true Date. So just keep this in mind if you continue..

Hi thanks a lot,

now im getting this
image
so the 11th moth is NA ?

You did not provide your actual date at the 11th position (your data stops at 8th). What was it originally?

Just out of curiosity: you have always the last day of the month twice? Maybe you (incorrectly) have the 31st of November in your data, even though it stops at 30th?

dput(head(df$Date,100))
c("07312021", "07312021", "08312021", "08312021", "09302021",
"09302021", "10312021", "10312021", "11312021", "11312021", "12312021",
"12312021", "01312022", "01312022", "02282022", "02282022", "03312022",
"03312022", "04302022", "04302022", "05312022", "05312022", "06302022",
"06302022", "07312021", "07312021", "08312021", "08312021", "09302021",
"09302021", "10312021", "10312021", "11312021", "11312021", "12312021",
"12312021", "01312022", "01312022", "02282022", "02282022", "03312022",
"03312022", "04302022", "04302022", "05312022", "05312022", "06302022",
"06302022", "07312021", "07312021", "08312021", "08312021", "09302021",
"09302021", "10312021", "10312021", "11312021", "11312021", "12312021",
"12312021", "01312022", "01312022", "02282022", "02282022", "03312022",
"03312022", "04302022", "04302022", "05312022", "05312022", "06302022",
"06302022", "07312021", "07312021", "08312021", "08312021", "09302021",
"09302021", "10312021", "10312021", "11312021", "11312021", "12312021",
"12312021", "01312022", "01312022", "02282022", "02282022", "03312022",
"03312022", "04302022", "04302022", "05312022", "05312022", "06302022",
"06302022", "07312021", "07312021", "08312021", "08312021")

Yes, looking at your data you have a 31st of November. This date does not exist, hence you cannot coerce it as a Date.

ahh let me just check that :smiley:

This topic was automatically closed 7 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.