1

Possible Duplicate:
Calculating moving average in R

I have written a rate of change function in R, defined as:

rateChange <- function(x) ((last(x)-first(x))/first(x))*100

It works wonderfully on various date ranges, such as the rate of change for 5 days, 10 days, 200 days, etc. However, I now have need to apply this function between every day. For example, to identify the rate of change for 5 days one would require the past 6 data observations.

Here is an example in Excel, and for clarity, I am trying to reproduce the "Rate of Change" column:

data

Thank you!

Community
  • 1
  • 1
jonnie
  • 745
  • 1
  • 13
  • 22

3 Answers3

6

I would suggest using TTR::ROC:

library(TTR)
roc <- c(18.89, 18.93, 18.55, 18.77, 18.87, 18.91)
ROC(roc, type="discrete")*100
# [1]         NA  0.2117522 -2.0073957  1.1859838  0.5327651  0.2119767
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 1
    @user1499626 - You mean "this is _a_ solution". There is almost always more than one way to do things in R. – Dason Dec 06 '12 at 20:22
4
x <- rnorm(5)
x
#[1] -0.48504744 -1.71843913  0.03890147 -2.11410329 -1.59765182
100*(tail(x, -1) - head(x, -1))/head(x, -1)
#[1]   254.28269  -102.26377 -5534.50754  -24.42887

If you need it to be the same length as the input vector you could just add an NA onto the end like this

c(100*(tail(x, -1) - head(x, -1))/head(x, -1), NA)
Dason
  • 60,663
  • 9
  • 131
  • 148
2

This is close but the math (outcome) isn't exactly the same:

 roc <- c(18.89, 18.93, 18.55, 18.77, 18.87, 18.91)
 sapply(seq_along(roc)[-1], function(i) 100*(roc[i] - roc[i-1])/roc[i-1])
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519