【发布时间】:2020-09-12 00:47:14
【问题描述】:
我有一个格式的数据集。如何将这些组合成日期格式列?
year mon day
1997 Jul 3
1997 Jul 1
1997 Sep 10
1997 Sep 1
1998 Oct 10
【问题讨论】:
标签: r date data-manipulation
我有一个格式的数据集。如何将这些组合成日期格式列?
year mon day
1997 Jul 3
1997 Jul 1
1997 Sep 10
1997 Sep 1
1998 Oct 10
【问题讨论】:
标签: r date data-manipulation
您可以将 3 列一起paste 并使用as.Date 将其转换为日期:
df <- transform(df, date = as.Date(paste(year, mon, day), '%Y %b %d'))
也可以从lubridate 使用ymd。
library(dplyr)
library(lubridate)
df %>% mutate(date = ymd(paste(year, mon, day)))
# year mon day date
#1 1997 Jul 3 1997-07-03
#2 1997 Jul 1 1997-07-01
#3 1997 Sep 10 1997-09-10
#4 1997 Sep 1 1997-09-01
#5 1998 Oct 10 1998-10-10
数据
df <- structure(list(year = c(1997L, 1997L, 1997L, 1997L, 1998L), mon = c("Jul",
"Jul", "Sep", "Sep", "Oct"), day = c(3L, 1L, 10L, 1L, 10L)),
class = "data.frame", row.names = c(NA, -5L))
【讨论】:
与@Ronak Shah 类似的答案,使用anytime 包
library(dplyr)
library(anytime)
library(stringr)
df %>%
mutate(year_mon_date = anydate(str_c(V1, V2, V3)))
# V1 V2 V3 year_mon_date
# 1 1997 Jul 3 1997-07-03
# 2 1997 Jul 1 1997-07-01
# 3 1997 Sep 10 1997-09-10
# 4 1997 Sep 1 1997-09-01
# 5 1998 Oct 10 1998-10-10
数据
structure(list(V1 = c(1997L, 1997L, 1997L, 1997L, 1998L), V2 = c("Jul",
"Jul", "Sep", "Sep", "Oct"), V3 = c(3L, 1L, 10L, 1L, 10L)), class = "data.frame", row.names = c(NA,
-5L))
【讨论】:
str_c(),但是你没有加载stringr。
您可以从lubridate 使用make_date()。
library(dplyr)
library(lubridate)
df %>%
mutate(date = make_date(year, match(mon, month.abb), day))
# year mon day date
# 1 1997 Jul 3 1997-07-03
# 2 1997 Jul 1 1997-07-01
# 3 1997 Sep 10 1997-09-10
# 4 1997 Sep 1 1997-09-01
# 5 1998 Oct 10 1998-10-10
其中month.abb 是一个内置向量,用于存储英文月份名称的缩写。
数据
df <- structure(list(year = c(1997L, 1997L, 1997L, 1997L, 1998L), mon = c("Jul",
"Jul", "Sep", "Sep", "Oct"), day = c(3L, 1L, 10L, 1L, 10L)),
class = "data.frame", row.names = c(NA, -5L))
【讨论】: