在 R 中使用 lubridate 仅提取日期和月份并保留日期格式

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

我想在不丢失 date 格式的情况下实现此目的

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

谢谢

这是一种方法,但有没有更快的方法并保持日期格式 (as.date)

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

我们可以直接使用 format

而不是创建两列后的 unite 步骤
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

或使用base R

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

基准

在稍微大一点的数据集上

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 

数据

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

另一个选择是:

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