0

I'm trying to do a time series analysis. Before that i need to index my date which is given in a YYYYMM format. I want to index it to to in-sample and out-of-sample analysis. I'm unable to index it.

I find similar questions in this platform but nothing seems to work in R. I tried using as.Date(), but unsuccessful so far.

Date <- c("198001","198002","198003","198004","198005")
X1 <- c("10", "20", "30", "40", "50")
X2 <- c("60", "70", "80", "90", "100")
df2 <- data.frame(Date,X1,X2)
df2

df2$Date <- as.Date(df2$Date, format = "%Y %m")
df2

But I'm getting under the Date variable

Expected Result:
        X1   X2
198001 10    60
198002 20    70
198003 30    80
189804 40    90
189005 50    100
sayan de sarkar
  • 185
  • 1
  • 10

1 Answers1

0

The Date needs a day too, so paste a day and it would work

as.Date(paste0(df2$Date, "01"), format = "%Y%m%d")
#[1] "1980-01-01" "1980-02-01" "1980-03-01" "1980-04-01" "1980-05-01"

If we need yearmon class, then use as.yearmon from zoo

library(zoo)
as.yearmon(df2$Date, '%Y%m')
#[1] "Jan 1980" "Feb 1980" "Mar 1980" "Apr 1980" "May 1980"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • The data do not have day, it has only year and month. This type of format i have not seen so far. So I was hoping someone can give me an idea. – sayan de sarkar Apr 13 '19 at 22:50
  • @sayandesarkar Okay, I showed, two options. The first is to paste a day e.g. 1 and then convert to `Date` or you can keep it as yearmon and use `as.yearmon` – akrun Apr 13 '19 at 22:51
  • @sayandesarkar let me know if you are fine with the solution – akrun Apr 13 '19 at 22:53
  • I tried the code mentioned above. Following is the error I'm getting: Error in charToDate(x) : character string is not in a standard unambiguous format – sayan de sarkar Apr 13 '19 at 22:55
  • @sayandesarkar Is it the same format as in the example you posted. If the format is different, then you need to change the format. Here, I used the format based on the example you showed – akrun Apr 13 '19 at 22:56
  • I have import a csv file into R, and the format are the same. Can you tell me how to directly import from csv into the above format? – sayan de sarkar Apr 13 '19 at 22:59
  • 1
    @sayandesarkar If it is year mon, you cannot specify `Date` class. After importing, you can change the format. Or use `read.zoo` with the `format` specified – akrun Apr 13 '19 at 23:00
  • 1
    @sayandesarkar Can you post the `dput(head(df2$Date))` i.e before the transformation – akrun Apr 13 '19 at 23:04
  • @sayandesarkar are you there or not? – akrun Apr 13 '19 at 23:06
  • Here it is: c(199509L, 199510L, 199511L, 199512L, 199601L, 199602L) – sayan de sarkar Apr 13 '19 at 23:10
  • 1
    @sayandesarkar If I name the object as `v1` and do `as.Date(paste0(v1, "01"), "%Y%m%d")# [1] "1995-09-01" "1995-10-01" "1995-11-01" "1995-12-01" "1996-01-01" "1996-02-01"` So, I am not sure how you are getting error because I used the same data as your data – akrun Apr 13 '19 at 23:11