将字符日期转换为R中的日期

Convert character date into date in R

这是我的数据集概览。 我想在 R

中将月份(格式 = 字符)转换为 formate:date

我试过 as.Date() as.Date(df$month, "%Y-%m") 但无法转换。 我用过 anytime() 和 as.POSIXct()

我想转换日期的原因是我需要通过变量 rime left_join 与其他数据集。

   crime_type    month       n   rate
   <chr>         <chr>   <int>  <dbl>
 1 Bicycle theft 2017-04    33 NA    
 2 Bicycle theft 2017-05    32  1.03 
 3 Bicycle theft 2017-06    36  0.889
 4 Bicycle theft 2017-07    39  0.923
 5 Bicycle theft 2017-08    52  0.75 
 6 Bicycle theft 2017-09    36  1.44 

另一个数据集在这里

 ym      unemploy_rate
   <chr>           <dbl>
 1 2017-1            4.6
 2 2017-2            4.6
 3 2017-3            4.5
 4 2017-4            4.4
 5 2017-5            4.4
 6 2017-6            4.3
 7 2017-7            4.3

我们可以paste一天用as.Date

df$month <- as.Date(paste0(df$month, "-01"), "%Y-%m-%d")

或者另一种选择是转换为 yearmon class 然后使用 as.Date

library(zoo)
df$month <- as.Date(as.yearmon(df$month))

更新

如果 objective 与 'ym' 列在 - 之后没有 0 的其他数据集 left_join,我们可以插入而不是对第一个数据进行格式更改

df2$ym <- sub("-(\d)$", "-0\1", df2$ym)