dplyr - How can I calculate the percentage change within a group for multiple columns in R? -
i have data frame id column, date column (12 months each id), , have 23 numeric variables. obtain percentage change month within each id. using quantmod package in order obtain percent change.
here example 3 columns (for simplicity):
id date v1 v2 v3 1 jan 2 3 5 1 feb 3 4 6 1 mar 7 8 9 2 jan 1 1 1 2 feb 2 3 4 2 mar 7 8 8
i tried use dplyr , summarise_each function, unsuccessful. more specifically, tried following (train name of data set):
library(dplyr) library(quantmod) group1<-group_by(train,examid) foo<-function(x){ return(delt(x)) } summarise_each(group1,funs(foo))
i tried use function in dplyr, not successful either (having bad night guess!).
i think issue delt function. when replace delt sum function:
foo<-function(x){ return(sum(x)) } summarise_each(group1,funs(foo))
the result every variable summed across date each id. how can percentage change month-over-month each id?
how using pct <- function(x) x/lag(x)
? 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
Comments
Post a Comment