Ian.T
Ian.T

Reputation: 1166

Extract only day and month with lubridate in R and conserve the date format

I would like to achieve this without loosing the date format

ID    Date         DayMonth
1     2004-02-06   06-02
2     2006-03-14   14-03
3     2007-07-16   16-07
...   ...          ...

Thanks

This is one way to do it but is there a faster way and keeping the date format (as.date)

date = df %>% mutate(DayDate=day(Date)) %>% mutate(MonthDate=month(Date)) %>%
  unite(DayMonth, c("DayDate", "MonthDate"), sep = "-")

Upvotes: 6

Views: 9683

Answers (2)

akrun
akrun

Reputation: 886938

Instead of the unite step after creating two columns, we can do this directly with format

library(dplyr)
df %>%
    mutate(DayMonth = format(as.Date(Date), "%d-%m"))
#  ID       Date DayMonth
#1  1 2004-02-06    06-02
#2  2 2006-03-14    14-03
#3  3 2007-07-16    16-07

Or using base R

df$DayMonth <- format(as.Date(df$Date), "%d-%m")

Benchmarks

On a slightly bigger dataset

library(tidyr)
library(lubridate)
df1 <- df %>% 
          uncount(1e6)
df1$Date <- as.Date(df1$Date)
system.time({df1 %>%
               mutate(DayDate=day(Date)) %>%
               mutate(MonthDate=month(Date)) %>%
               unite(DayMonth, c("DayDate", "MonthDate"), sep = "-")
                })
# user  system elapsed 
#  1.998   0.030   2.014 

system.time({df1 %>%
                mutate(DayMonth = format(Date, "%d-%m"))})
#   user  system elapsed 
#  1.119   0.001   1.118 

data

df <- structure(list(ID = 1:3, Date = c("2004-02-06", "2006-03-14", 
"2007-07-16")), row.names = c(NA, -3L), class = "data.frame")

Upvotes: 6

Freddy A.
Freddy A.

Reputation: 31

other alternative is:

date <-  df %>% as.Date(paste0(as.character(day(Date)), '-',as.character(month(Date))), format='%d-%m')

Upvotes: 1

Related Questions