1

I have a data which is of of the following output:

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

I want to to convert Date to date format so I can read it as time series. I am using the following code to convert it to date format:

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

But it gives me NA values in Date column. Any pointers on this?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
CyberPunk
  • 1,297
  • 5
  • 18
  • 35

2 Answers2

3

you can simply extend the string prior to casting it to date.

Date=as.Date(paste(Date,"-01"),'%Y-%m-%d')
webmite
  • 575
  • 3
  • 6
2

You could use parse_date from the lubridate package:

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"
johannes
  • 14,043
  • 5
  • 40
  • 51