I'm trying to see if there is a way to vectorize a calculation I performed. I searched for this answer and couldn't find what I needed.
I have a vector of growth rates. Each one represents one period (one year in my case). I want to apply this vector to some principal amount. Then, after the first growth rate is applied to the principal, use the result from the first iteration and apply the second growth element to the new value.
Here's some code for reproduction (all in base
):
# Vector of interest or inflation rates
RateVector <- c(0.02, 0.03, 0.04, 0.05, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01) # forecasted rates
Principal <- data.frame(Principal = 1000000) # actual value of indicator in most recent period as data frame (list)
Here was my attempt to vectorize:
sapply(Principal, "*", 1 + cumsum(RateVector))
The problem with this is that the sapply
function does not save the new amount and instead applies the vector of rates to the same initial principal. This is actually what I expected from this code. I don't know how to go about saving the new value after each iteration from element to element.
This is how I solved the problem, using a loop:
AmountVector <- Principal # initialize output vector
# Compound growth growth calculation loop
for(i in 1:length(RateVector)){
Principal = Principal * (1 + RateVector)[i]
AmountVector <- rbind(AmountVector,Principal)
}
# Print result
AmountVector