time series - Apply a function rowwise for calculating percentage changes in R -


this question has answer here:

i have yearly time series data in long format @ group-state-brand level. want apply function calculate growth rates yoy every level.

basically (currentvalue/previous value) -1

find below extract of data:

grp sta brnd     yr      sls   al  ben's   2012    29770   al  ben's   2013    23357   al  ben's   2014    22442   al  ben's   2015    21848   al  ben's   2016    13799 b   ca  scott's 2012    1079 b   ca  scott's 2013    11178 b   ca  scott's 2014    14778 b   ca  scott's 2015    15241 b   ca  scott's 2016    10569 c   tx  joey's  2012    1673 c   tx  joey's  2013    1290 c   tx  joey's  2014    899 c   tx  joey's  2015    732 c   tx  joey's  2016    294 

basically, each unique level of grp-state-brand 5 rows.

grp sta brnd     yr      sls    grwth   al  ben's   2012    29770      al  ben's   2013    23357   -22%   al  ben's   2014    22442   -4%   al  ben's   2015    21848   -3%   al  ben's   2016    13799   -37% b   ca  scott's 2012    1079     b   ca  scott's 2013    11178   936% b   ca  scott's 2014    14778   32% b   ca  scott's 2015    15241   3% b   ca  scott's 2016    10569   -23% c   tx  joey's  2012    1673     c   tx  joey's  2013    1290    -23% c   tx  joey's  2014    899     -30% c   tx  joey's  2015    732     -19% c   tx  joey's  2016    294     -60% 

df=data.frame(grp = c(rep("a",5),rep("b",5),rep("c",5)), sta = c(rep("al",5),rep("ca",5),rep("tx",5)),            brnd = c(rep("ben's",5),rep("scott's",5),rep("joey's",5)),            yr=rep(c(2012,2013,2014,2015,2016),3),            sls = c(29770,23357,22442,21848,13799,1079,11178,14778,15241,10569,1673,1290,899,732,294))   ddply(df, .(grp,sta,brnd),mutate, y = sprintf("%.2f%%",c(na,100*diff(sls)/sls[-length(sls)])))      grp sta    brnd   yr   sls       y 1     al   ben's 2012 29770     na% 2     al   ben's 2013 23357 -21.54% 3     al   ben's 2014 22442  -3.92% 4     al   ben's 2015 21848  -2.65% 5     al   ben's 2016 13799 -36.84% 6    b  ca scott's 2012  1079     na% 7    b  ca scott's 2013 11178 935.96% 8    b  ca scott's 2014 14778  32.21% 9    b  ca scott's 2015 15241   3.13% 10   b  ca scott's 2016 10569 -30.65% 11   c  tx  joey's 2012  1673     na% 12   c  tx  joey's 2013  1290 -22.89% 13   c  tx  joey's 2014   899 -30.31% 14   c  tx  joey's 2015   732 -18.58% 15   c  tx  joey's 2016   294 -59.84% 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -