Nina van Bruggen
Nina van Bruggen

Reputation: 523

How do I change a ymd date to a dmy date with lubridate?

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"))

Upvotes: 1

Views: 3141

Answers (3)

Mickey Yang
Mickey Yang

Reputation: 31

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

Upvotes: 0

Vishal Katti
Vishal Katti

Reputation: 652

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

Upvotes: 0

Aur&#232;le
Aur&#232;le

Reputation: 12819

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"

Upvotes: 2

Related Questions