Search code examples
rapache-sparksparkr

add_months function in Spark R


I have a variable of the form "2020-09-01". I need to increase and decrease this by 3 months and 5 months and store it in other variables. I need a syntax in Spark R.Thanks. Any other method will also work.Thanks, Again In R following code works fine

y <- as.Date(load_date,"%Y-%m-%d") %m+% months(i)

The code below didn't work. Error says

unable to find an inherited method for function ‘add_months’ for signature ‘"Date", "numeric"

 loaddate = 202009
 year <- substr(loaddate,1,4)
 month <- substr(loaddate,5,6)
 load_date <- paste(year,month,"01",sep = "-")
 y <- as.Date(load_date,"%Y%m%d")
 y1 <- add_months(y,-3)

Expected Result - 2020-06-01


Solution

  • The lubridate package makes dealing with dates much easier. Here I have shuffled as.Date up a step, then simply subtract 3 months.

    library(lubridate)
    
    loaddate = 202009
    year <- substr(loaddate,1,4)
    month <- substr(loaddate,5,6)
    load_date <- as.Date(paste(year,month,"01",sep = "-"))
    new_date <- load_date - months(3)
    

    new_date Output:

    Date[1:1], format: "2020-06-01"