r:将字符串转换为日期

r: convert a string to date

我有一个这样的字符串:

201601 
201603 
201604 
201606 
201501

我想像这样转换为日期:

2016-01
2016-03
2016-04
2016-06
2015-01

我试过:df$month_key=as.Date(df$month_key,format="YYYYmm") 但是它要求出处,我们不需要关心。 有没有办法做到这一点,或者在整列的字符 4 和 5 之间添加破折号? 谢谢

我们可以使用sub在前4个字符和接下来的2个字符之间创建一个-。匹配四个字符(.{4}),将其放在捕获组中( (...)),然后是另一个捕获组中接下来的 2 个字符,将其替换为这些组的反向引用(\1\2),然后在它们之间添加 - .

df1$Col <- sub('(.{4})(.{2})', "\1-\2", df1$month_key)
df1$Col
#[1] "2016-01" "2016-03" "2016-04" "2016-06" "2015-01"

另一种选择是substr/paste

with(df1, paste(substr(month_key, 1,4), substr(month_key, 5, 6), sep="-"))

不过,Dateclass也有一天。因此,要将原始列转换为 'Date',我们可以附加任何一天,也许附加 01 并使用 as.Date

中的格式
as.Date(paste0(df1$month_key, "01"), "%Y%m%d")

数据

df1 <- structure(list(Col = c(201601L, 201603L, 201604L, 201606L, 201501L
 )), .Names = "month_key", class = "data.frame", row.names = c(NA, -5L))