【发布时间】:2020-05-27 12:26:33
【问题描述】:
我有一列包含每月日期的此类类型(月数、_、年):
Date
9_2018
1_2013
12_2014
等等
我想将此日期格式转换为以下形式的日期(年、月):
New_Date
201809
201301
201412
我该怎么做?
【问题讨论】:
标签: r date datatable substring lubridate
我有一列包含每月日期的此类类型(月数、_、年):
Date
9_2018
1_2013
12_2014
等等
我想将此日期格式转换为以下形式的日期(年、月):
New_Date
201809
201301
201412
我该怎么做?
【问题讨论】:
标签: r date datatable substring lubridate
我们可以使用zoo::as.yearmon转换日期,然后使用format获取所需格式的数据。
format(zoo::as.yearmon(df$Date, "%m_%Y"), "%Y%m")
#[1] "201809" "201301" "201412"
或者也可以在基础 R 中通过将任意日期粘贴到我们拥有的年月值来完成。
format(as.Date(paste0("1_", df$Date), "%d_%m_%Y"), "%Y%m")
数据
df <- structure(list(Date = structure(c(3L, 1L, 2L), .Label = c("1_2013",
"12_2014", "9_2018"), class = "factor")),
class = "data.frame",row.names = c(NA, -3L))
【讨论】:
为月份填充零,然后在“_”处拆分:
library(stringr)
mon <- sapply(strsplit(Date, "_"), FUN="[", 1)
mon <- str_pad(mon, width=2, pad="0")
year <- sapply(strsplit(Date, "_"), FUN="[", 2)
paste0(year,mon)
[1] "201809" "201301" "201412"
【讨论】: