Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

loops

r

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))
like image 839
LostSamurai Avatar asked Jan 29 '16 07:01

LostSamurai


People also ask

Should you avoid for loops in R?

For that reason, it might make sense for you to avoid for-loops and to use functions such as lapply instead. This might speed up the R syntax and can save a lot of computational power! The next example explains how to use the lapply function in R.

Which in built functions in R can be used to optimize tasks which require looping?

The combination of split() and a function like lapply() or sapply() is a common paradigm in R. The basic idea is that you can take a data structure, split it into subsets defined by another variable, and apply a function over those subsets.

Why is R so slow with loops?

There is a lot of overhead in the processing because R needs to check the type of a variable nearly every time it looks at it. This makes it easy to change types and reuse variable names, but slows down computation for very repetitive tasks, like performing an action in a loop.

How do you control the looping statements in R?

repeat and break Statement in R We use break statement inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. While in a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.


1 Answers

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.

like image 138
A. Webb Avatar answered Oct 06 '22 01:10

A. Webb