将“2015M01”形式的变量转换为 R 中的日期格式?

Converting variables in form of "2015M01" to date format in R?

我有一个日期框架 df,它看起来像这样:

 month  values
2012M01  99904
2012M02  99616
2012M03  99530
2012M04  99500
2012M05  99380
2012M06  99103
2013M01  98533
2013M02  97600
2013M03  96431
2013M04  95369
2013M05  94527
2013M06  93783

以"M01"、"M02"...等形式书写的月份。 现在我想将此列转换为日期格式,有没有办法在 R 中使用 lubridate 进行转换?

我还想 select 包含每年某个月份的列,就像这些年只有三月的列一样,最好的方法是什么?

像这样会得到它:

raw <- "2012M01"

dt <- strptime(raw,format = "%YM%m")

dt 将采用 Posix 格式。 strptime 函数将分配一个“1”作为一个月中的默认日期,使其成为一个完整的日期。

简而言之,日期需要年月日,因此您不能直接转换为日期格式。您有 2 个选择。

选项 1:使用 zoo::as.yearmon.

转换为年月格式
library(zoo)
df$yearmon <- as.yearmon(df$month, "%YM%m")
# you can get e.g. month from that
months(df$yearmon[1])
# [1] "January"

选项 2:通过假设日期始终是该月的第一天来转换为日期。

df$date <- as.Date(paste(df$month, "01", sep = "-"), "%YM%m-%d")

对于 selection(我想你的意思是 select 行,而不是列),你已经拥有了你需要的一切。例如,到 select 仅 2013 年 3 月:

library(dplyr)
df %>% filter(month == "2013M03")