为什么在解析年月格式的日期时会获得NA?

时间:2018-05-23 21:17:20

标签: r date

我有一个具有以下输出的数据:

Observations: 13
Variables: 7
$ Date      <chr> "2017-04", "2017-05", "2017-06", "2017-07", "2017-08", "2017-09", "2017-10", "2017-11", "2017-12", "2018-01", "2018-02", "2018-03", "2018-04"
$ Mobile    <dbl> 51.95, 51.70, 53.03, 53.99, 52.64, 52.29, 50.87, 50.02, 52.48, 51.92, 51.82, 51.56, 51.20
$ Desktop   <dbl> 43.23, 43.59, 42.19, 41.22, 42.75, 43.29, 44.78, 45.68, 43.26, 43.87, 44.12, 44.27, 44.66
$ Tablet    <dbl> 4.82, 4.71, 4.78, 4.79, 4.62, 4.42, 4.35, 4.30, 4.26, 4.21, 4.06, 4.18, 4.14
$ MobilePk  <dbl> 68.59, 68.28, 69.43, 69.47, 67.65, 69.90, 68.09, 67.26, 68.31, 68.73, 69.83, 70.93, 70.56
$ DesktopPk <dbl> 28.58, 29.13, 27.99, 28.17, 30.10, 27.88, 29.82, 30.60, 29.64, 29.32, 28.30, 27.21, 27.63
$ TabletPk  <dbl> 2.83, 2.59, 2.57, 2.36, 2.25, 2.22, 2.09, 2.14, 2.05, 1.95, 1.87, 1.86, 1.81

我想将Date转换为日期格式,以便我可以将其作为时间序列阅读。 我使用以下代码将其转换为日期格式:

Date=as.Date(Date,'%Y-%m')

但它在NA列中为我提供了Date个值。关于这个的任何指示?

2 个答案:

答案 0 :(得分:3)

您可以在将其转换为日期之前简单地扩展字符串。

Date=as.Date(paste(Date,"-01"),'%Y-%m-%d')

答案 1 :(得分:2)

您可以使用parse_date包中的lubridate

library(lubridate)

Date <- c("2017-04", "2017-05", "2017-06")
parse_date_time(Date, "ym")
## [1] "2017-04-01 UTC" "2017-05-01 UTC" "2017-06-01 UTC"