0

So, let's say I have data with a column date.

library(dplyr)
library(lubridate)

df <- data.frame(
  nr = c(1, 2),
  date = c(20170131, 20081028)
)

df2 <- df %>% 
  mutate(date = ymd(date))

Now my data has the dates in proper date format year-month-date. But what if I want to change that to d-m-y format in one statement? The only solution I have is with the format function. But is there a lubridate solution as well?

df3 <- df2 %>% 
  mutate(date = format(date, "%d/%m/%Y"))
Nina van Bruggen
  • 393
  • 2
  • 13
  • 2
    `format` is the go-to function for that purpose. I'm not sure there is a need for another function that does the same thing. – Maël Sep 02 '22 at 10:01
  • It seems there is some confusion with the OP. Dates have a specific format. Strings are no Dates anymore and every other formatting of a Date makes a Date a String again. Functions from lubridate like ymd, mdy, etc. Read in Strings and make it a Date which have one specific format. Then you can use format or the lubridate stamp function to convert the Date back to the String format you wish. If you want to keep it a Date in another format, you simply cannot. – Merijn van Tilborg Sep 02 '22 at 13:21

3 Answers3

2

Lubridate has the dedicated stamp function.

Example use from the documentation:

D <- ymd("2010-04-05") - days(1:5)
stamp("March 1, 1999")(D)
#> Multiple formats matched: "%Om %d, %Y"(1), "March %Om, %Y"(1), "%B %d, %Y"(1), "March %m, %Y"(1)
#> Using: "%B %d, %Y"
#> [1] "April 04, 2010" "April 03, 2010" "April 02, 2010" "April 01, 2010"
#> [5] "March 31, 2010"
Aurèle
  • 12,545
  • 1
  • 31
  • 49
  • Interesting, but not really what I was looking for. I guess the format function is the best option still. – Nina van Bruggen Sep 02 '22 at 11:34
  • What features are lacking from `format`, that you'd expect from a lubridate function? If none, why look for a replacement? – Aurèle Sep 02 '22 at 14:49
0

Lubridate also has the dmy() function you could use.

Vishal Katti
  • 532
  • 2
  • 6
0

Please kindly find my solution below. I hope this helps.

Here is my code:

library(dplyr)
library(lubridate)

df <- data.frame(
  nr = c(1, 2),
  date = c(20170131, 20081028)
)

df %>% 
  mutate(date = ymd(date)) %>%
  mutate(date_dmy = format(date, "%d%m%Y")) %>%
  View()

enter image description here