I have a data frame with an ID column, a date column (12 months for each ID), and I have 23 numeric variables. I would like to obtain the percentage change by month within each
How about using
pct <- function(x) x/lag(x)
? (or (x/lag(x)-1)*100
, or however you wish to specify pct change exactly)
e.g.,
pct(1:3)
[1] NA 2.0 1.5
Edit: Adding Frank's suggestion
pct <- function(x) {x/lag(x)}
dt %>% group_by(ID) %>% mutate_each(funs(pct), c(V1, V2, V3))
ID Date V1 V2 V3
1 Jan NA NA NA
1 Feb 1.500000 1.333333 1.2
1 Mar 2.333333 2.000000 1.5
2 Jan NA NA NA
2 Feb 2.000000 3.000000 4.0
2 Mar 3.500000 2.666667 2.0