Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage change in an R data frame

Tags:

r

time-series

I have a time series object in R with multiple vectors. I would like to calculate the period-over-period percentage change at each point in time (save t = 1, which would obviously be NA) for each vector.

> data <- ts(data.frame(x1=c(1:10), x2=c(11:20), x3=c(21:30)), start = c(2010,3), frequency = 4) > data         x1 x2 x3 2010 Q3  1 11 21 2010 Q4  2 12 22 2011 Q1  3 13 23 2011 Q2  4 14 24 2011 Q3  5 15 25 2011 Q4  6 16 26 2012 Q1  7 17 27 2012 Q2  8 18 28 2012 Q3  9 19 29 2012 Q4 10 20 30 
like image 832
E. Vincenti Avatar asked Jan 30 '13 22:01

E. Vincenti


People also ask

How do you find the percent change in a data set?

First: work out the difference (increase) between the two numbers you are comparing. Then: divide the increase by the original number and multiply the answer by 100. % increase = Increase ÷ Original Number × 100. If your answer is a negative number, then this is a percentage decrease.

How do I calculate a percentage in R?

To calculate percent, we need to divide the counts by the count sums for each sample, and then multiply by 100. This can also be done using the function decostand from the vegan package with method = "total" .


1 Answers

Try this:

R> data/stats::lag(data,-1) - 1          data.x1   data.x2   data.x3 2010 Q4 1.000000 0.0909091 0.0476190 2011 Q1 0.500000 0.0833333 0.0454545 2011 Q2 0.333333 0.0769231 0.0434783 2011 Q3 0.250000 0.0714286 0.0416667 2011 Q4 0.200000 0.0666667 0.0400000 2012 Q1 0.166667 0.0625000 0.0384615 2012 Q2 0.142857 0.0588235 0.0370370 2012 Q3 0.125000 0.0555556 0.0357143 2012 Q4 0.111111 0.0526316 0.0344828 R>  
like image 95
Dirk Eddelbuettel Avatar answered Oct 08 '22 04:10

Dirk Eddelbuettel