Search code examples
rdate-formatfacebook-prophet

Prophet Date Format R


year_month   amount_usd
201501       -390217.24
201502       230944.09
201503       367259.69
201504       15000.00
201505       27000.21
201506       38249.65

df <- structure(list(year_month = 201501:201506, amount_usd = c(-390217.24, 
230944.09, 367259.69, 15000, 27000.21, 38249.65)), class = "data.frame", row.names = c(NA, 
-6L))

I want to bring it in to DD/MM/YYYY format for usability in Prophet Forecasting code.

this is what i have tried so far.

for (loopitem in loopvec){
  df2 <- subset(df, account_id==loopitem)
  df3 <- df2[,c("year_month","amount_usd")]
  df3$year_month <- as.Date(df3$year_month, format="YYYY-MM", origin="1/1/1970")
  try <- prophet(df3, seasonality.mode = 'multiplicative')
}

Error in fit.prophet(m, df, ...) : Dataframe must have columns 'ds' and 'y' with the dates and values respectively.


Solution

  • You need to paste the day number (I'm just using the first) to the year_month values, then can use the ymd() function from lubridate to convert the column to a date object.

    library(dplyr)
    library(lubridate)
    
    mutate_at(df, "year_month", ~ymd(paste(., "01")))
    
      year_month amount_usd
    1 2015-01-01 -390217.24
    2 2015-02-01  230944.09
    3 2015-03-01  367259.69
    4 2015-04-01   15000.00
    5 2015-05-01   27000.21
    6 2015-06-01   38249.65