This question already has answers here:
Closed 7 years ago.
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:
Thank you!
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
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)
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])