1

I have a column of dates that were read in as character. I want to produce a data class with my desired format (say, US-style, 08/28/2020). But, all solutions to change format, produce character class, or produce date class with standard format (2020-08-28) This is a reproducible example:

df1 <- data.frame(date=c("08/27/2020", "08/28/2020", "08/29/2020"), cases=c(5,6,7))
class(df1$date)


df1$date1<- format(as.Date(df1$date, format = "%m/%d/%Y"), "%m/%d/%Y")
class(df1$date1)

df1$date2<-as.Date(parse_date_time(df1$date,"%m/%d/%Y"))
class(df1$date2)

df1$date3<- as.Date(df1$date, format = "%m/%d/%Y")
class(df1$date3)

df1

As you can see data1 has my desired format while it is not date class. In addition, date2 and date3 are Date class while they produce undesired format.

   date    cases  date1      date3      date2

1| 08/27/2020 | 5 | 08/27/2020 |2020-08-27 | 2020-08-27|

2| 08/28/2020 | 6 | 08/28/2020 |2020-08-28 | 2020-08-28|

3| 08/29/2020 | 7 | 08/29/2020 |2020-08-29 | 2020-08-29|

Where am I going wrong?

  • Check again. Running `as.Date(df1$date, format = "%m/%d/%Y")` returns an object of class `Date` on my machine. – stefan Jan 07 '22 at 12:08
  • 1
    Date class is of fixed format `YYYY-MM-DD` in R. Anything else would be character class. – Ronak Shah Jan 07 '22 at 12:45
  • As you see in the links above, it is possible to change print format, but please also note relevant objections in comments therein. – Henrik Jan 07 '22 at 13:10
  • Thank you @setfan. Yes. It returns an object of class date but the output format is not desired. – Amir Habibdoust Jan 07 '22 at 19:36

2 Answers2

1

A Date class is always shown like "2020-08-27" in R. That's R's standard Date. To reformat it into something different you can use strftime. It assumes a Date class and outputs a character object with your desired format, e.g.

df1$date2
[1] "2020-08-27" "2020-08-28" "2020-08-29"

class(df1$date2)
[1] "Date"

strftime(df1$date2, format="%m/%d/%Y")
[1] "08/27/2020" "08/28/2020" "08/29/2020"

class(strftime(df1$date2, format="%m/%d/%Y"))
[1] "character"
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
1

When dealing with dates and time lubridate package is really handy: https://lubridate.tidyverse.org/.

In this case we could use mdy function (month, day, year) for date and date1.

library(lubridate)
library(dplyr)
df1 %>% 
  mutate(across(c(date, date1), mdy))
  date       cases date1      date3     
  <date>     <dbl> <date>     <date>    
1 2020-08-27     5 2020-08-27 2020-08-27
2 2020-08-28     6 2020-08-28 2020-08-28
3 2020-08-29     7 2020-08-29 2020-08-29
TarJae
  • 72,363
  • 6
  • 19
  • 66