'Year-on-year change column in the data frame of monthly data

I am looking for the solution to my task. It is to add a new column to the data frame, which contains monthly data, that would have year-on-year change for each record that has a corresponding record of same month a year ago.

So, my code as of now is:

library(blsAPI)
cpi       <- blsAPI("CUUR0000SA0",2,TRUE)      
cpi$value <- as.numeric(cpi$value)
cpi$date  <- as.Date(                        
     paste0("1 ",cpi$periodName," ",cpi$year), 
     format = "%d %B %Y")
cpi <- cpi[order(cpi$date),]

I would like to add new column with YoY change value for cpi$value column.

r


Solution 1:[1]

Something like:

df <- data.frame(Date = c("2021-01-16", "2017-05-09"))
df |> dplyr::mutate(new = as.Date(Date) + 365)
#>         Date        new
#> 1 2021-01-16 2022-01-16
#> 2 2017-05-09 2018-05-09

library(lubridate)

df |>
  dplyr::mutate(new = as_date(Date) %m+% years(1))
#>         Date        new
#> 1 2021-01-16 2022-01-16
#> 2 2017-05-09 2018-05-09

Created on 2022-02-11 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grzegorz Sapijaszko