Reputation: 63
For example, I’m currently working on a function that allows you to see how much money you might have if you invested in the stock market. It’s currently using a loop structure, which is really irritating me, because I know there probably is a better way to code this and leverage vectors in R. I’m also creating dummy vectors before running the function, which seems a bit strange too.
Still a beginner at R (just started!), so any helpful guidance is highly appreciated!
set.seed(123)
##Initial Assumptions
initialinvestment <- 50000 # e.g., your starting investment is $50,000
monthlycontribution <- 3000 # e.g., every month you invest $3000
months <- 200 # e.g., how much you get after 200 months
##Vectors
grossreturns <- 1 + rnorm(200, .05, .15) # approximation of gross stock market returns
contribution <- rep(monthlycontribution, months)
wealth <- rep(initialinvestment, months + 1)
##Function
projectedwealth <- function(wealth, grossreturns, contribution) {
for(i in 2:length(wealth))
wealth[i] <- wealth[i-1] * grossreturns[i-1] + contribution[i-1]
wealth
}
##Plot
plot(projectedwealth(wealth, grossreturns, contribution))
Upvotes: 6
Views: 127
Reputation: 26446
I would probably write
Reduce(function(w,i) w * grossreturns[i]+contribution[i],
1:months,initialinvestment,accum=TRUE)
but that's my preference for using functionals. There is nothing wrong with your use of a for
loop here.
Upvotes: 10