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



这是我的数据集概述。我想将月份(格式=字符(转换为R 中的甲酸盐:日期

我尝试过作为.Date((as.Date(df$month, "%Y-%m"),但无法转换。我使用了anytime((和作为.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类,然后使用as.Date

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

更新

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

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

最新更新