Is there a way to simplify functions in R that use loops?

For example, Im is currently working on a feature that lets you know how much money you have if you invest in the stock market. I am currently using a loop structure that really annoys me because I know that probably the best way to code this and use vectors in R. Im also creates dummy vectors before running the function, which seems a little strange too.

New to R (just getting started!), So any helpful guide is much appreciated!

set.seed(123) ##Initial Assumptions initialinvestment <- 50000 # eg, your starting investment is $50,000 monthlycontribution <- 3000 # eg, every month you invest $3000 months <- 200 # eg, 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)) 
+6
source share
1 answer

I would probably write

 Reduce(function(w,i) w * grossreturns[i]+contribution[i], 1:months,initialinvestment,accum=TRUE) 

but I prefer to use functionals. There is nothing wrong with using a for loop.

+10
source

All Articles