1

I am struggling with a to convert an simple month year format to tsibble. I have this dataset,

a <- c(12014, 22014, 32014, 42014, 52014, 62014, 72014, 82014, 92014, 102014, 112014, 122014, 
       12015, 22015, 32015, 42015, 52015, 62015, 72015, 82015, 92015, 102015, 112015, 122015,
       12014, 22014, 32014, 42014, 52014, 62014, 72014, 82014, 122014)
b <- rnorm(33, mean = 12, sd = 8)

dt <- data.frame(a, b)

Here the vector a should be the time variable. It is not necessarily unbroken. That means it is possible that I have implicite missing value.

as.Date(dt$a, origin = "01-1901")
library(tidyverse)
as_tsibble(dt)

What I understood is, first I need to convert the data into 'as.Date' and the make the data into tsibble.

I am getting the following error message,

> as.Date(dt$a, origin = "01-1901")
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

Is there anyone who can help me to find the way around?

zx8754
  • 52,746
  • 12
  • 114
  • 209
JontroPothon
  • 127
  • 1
  • 9

1 Answers1

1

We can pad 0 at the beginning, convert to yearmon with as.yearmon and coerce it to 'Date' class with as.Date

library(zoo)
dt$a <- as.Date(as.yearmon(sprintf("%06d", dt$a), "%m%Y"))
dt$a
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2014-04-01" "2014-05-01" "2014-06-01" "2014-07-01" "2014-08-01" "2014-09-01" "2014-10-01" "2014-11-01"
#[12] "2014-12-01" "2015-01-01" "2015-02-01" "2015-03-01" "2015-04-01" "2015-05-01" "2015-06-01" "2015-07-01" "2015-08-01" "2015-09-01" "2015-10-01"
#[23] "2015-11-01" "2015-12-01" "2014-01-01" "2014-02-01" "2014-03-01" "2014-04-01" "2014-05-01" "2014-06-01" "2014-07-01" "2014-08-01" "2014-12-01"

NOTE: when we convert to tsibble, make sure the duplicate dates are removed

akrun
  • 874,273
  • 37
  • 540
  • 662
  • This works. However, my data is a end-of-month data. So I want to omit the day from the date. I have added another column to convert it to `tssible` as I want to avoid the duplicate error. – JontroPothon Nov 16 '19 at 21:24
  • @JontroPothon You can use `dt[!duplicated(dt$a),]` to remove the duplicateese – akrun Nov 16 '19 at 21:47
  • I am trying to do a one step forecast using fable and it is generating 1 day forecast instead of one month forecast. Is there any way I can have it without days? Something like this should work, `time <- rep(yearmonth("2014 Jan") + 0:59, times = 218)`. – JontroPothon Nov 21 '19 at 08:59
  • @JontroPothon Can you please post as a new question with a reproducible example – akrun Nov 21 '19 at 17:39