0

I have a timeseries dataset in R with a monthly temporal resolution. But in the data frame there is day/month/year included which does not make any sense, I mean the (day). So firstly I have converted the date into the as.Date format by using this code.

Data$Month <- as.Date(Data$Month, format = '%m/%d/%Y')

Result: > `head(Data$Month)`
[1] "2016-01-01" "2016-01-01" "2016-01-01" "2016-01-01" "2016-01-01"
[6] "2016-01-01"

Which works perfectly. Now I have created another column by using this code from the previous Month column which include only Month_Yr.

Data$Month_Yr <- format(as.Date(Data$Month), "%m/%Y")

Result: > head(Data$Month_Yr)
[1] "01/2016" "01/2016" "01/2016" "01/2016" "01/2016" "01/2016"

This newly column (Month_Yr) class in Character. Now I want to change this newly created column into as.Date format by using this code.

Data$Month_Yr <- as.Date(Data$Month_Yr, format = "%m/%Y")

But when I did this column is converted into NA values.

Result: > head(Data$Month_Yr)
[1] NA NA NA NA NA NA
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Ellee
  • 21
  • 1
  • 8
  • 1
    The Date type can't handle month/year values. It needs a proper date (it needs to know what day of the month it is.) See duplicate for options (like hard coding the first day of the month) or using a different type. – MrFlick Feb 16 '20 at 02:16
  • When you put a character result back into a dataframe column, it becomes a `factor`-class. There is a yearmon class defined in the zoo package. – IRTFM Feb 16 '20 at 02:49
  • @MrFlick Thanks for the correction. I've had so much trouble over the years with factors that I immediately assume that is the root of any question. – IRTFM Feb 16 '20 at 03:15

0 Answers0