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


for example, i’m working on function allows see how money might have if invested in stock market. it’s using loop structure, irritating me, because know there better way code , leverage vectors in r. i’m creating dummy vectors before running function, seems bit strange too.

still beginner @ r (just started!), helpful guidance highly appreciated!

set.seed(123) ##initial assumptions  initialinvestment <- 50000 # e.g., starting investment $50,000 monthlycontribution <- 3000 # e.g., every month invest $3000  months <- 200 # e.g., how 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)) 

i write

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

but that's preference using functionals. there nothing wrong use of for loop here.


Comments