I have a simple time series dataset with 10 variables - I want to create a for loop (or a function) that creates a 'change from previous month' variable and a 'percent change from previous month variable' for each variable in the timeseries (except for the date). I know I can simply write code for each particular column but would like to optimize this since there are a lot of columns.
Here is what my data looks like, "Date", "Sales", "Price" are some column names:
+----+---+---+---+---+---+---+---+--
| Date | Sales | Price |
+----+---+---+---+---+---+---+---+--
| 01Aug2019 | 4 | 15 |
| 01Sept2019 | 6 | 30 |
| 01Oct2019 | 10 | 44 |
+----+---+---+---+---+---+---+---+--
Here is what I want it to look like with the use of the for loop (or any function)
+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| Date | Sales | chg_Sales | pct_chg_Sales | Price | chg_Price | pct_chg_Price|
+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 01Aug2019 | 4 | NA |NA | 15 | NA |NA |
| 01Sept2019 | 6 | 2 |50% | 30 | 15 |100% |
| 01Oct2019 | 10 | 4 |66% | 44 | 14 |46% |
+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
I tried the code below but it did not work
add_column <- function (x, y){
setDT (x)[,pct_chg_y:= (y - shift (y,1, type="lag")/shift (,1, type="lag")*100]
}