# Optimization of While and For loops

#### Morten

##### New Member
Hi

I am relatively new to R and have been using an algorithm for a project.
I is in this case about 400 million. It is taking a rather long time to run ~20 - 30 minutes, and I was curious if there was a better way of running this?

dPNProbExpand is a vector of probabilities, 1 row shorter than I. So naturally it should take some time, I was just wondering if this setup is the best.

Code:
I = 400000000
tao = 1
V_b <- matrix(0, I, 1)
V_s <- matrix(0, I, 1)

while( I >= (tao*V)) {

for( j in ((((tao - 1)*V)+1):(tao*V))){

V_b[tao] = V_b[tao] + dPNProbExpand[j]

}
V_s[tao] = (V - V_b[tao])
tao = tao + 1
}

#### bryangoodrich

##### Probably A Mammal
V is undefined

and no, this set up is far from best. You're not taking advantage of any vectorized operations in R. Rarely do you need to do a for loop to traverse the points of a vector. You can use the *apply family of functions (e.g., apply, lapply, tapply) to do that far more efficiently or use functions that are designed to do it for you (e.g., x + 2 applies "+ 2" to each point in the vector x).

Since R is conveniently a functional language, you can define functions to do some of these steps for you, so create your own vectorized functions, often out of functions already there in R, and apply them instead of your looping.

#### Morten

##### New Member
V is set based on earlier parameters, but it will usually be a large number say 4000.

Thanks for your input, I am looking in to rewriting this.