我想在不丢失的情况下实现这个目标。日期 格式化
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 = "-")
另一个选择是。
date <- df %>% as.Date(paste0(as.character(day(Date)), '-',as.character(month(Date))), format='%d-%m')
取而代之的是... unite
步,在创建两列后,我们可以直接用 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
或使用 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")