我想在不丢失日期格式的情况下实现这一点
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")
关于r - 在 R 中使用 lubridate 仅提取日期和月份并保留日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62269705/