One of the advantages of using R is its vectorization , which means that it can easily perform operations on the entire vector at the same time, and not to scroll through each element.
As David Arenburg noted in a comment (with updates thanks to BondedDust and Dominic Comtois), you can do this in your case:
practice[-1] / head(practice, -1) - 1
What does it do?
practice[-1] refers to the entire vector except the first element.
> practice[-1] [1] 2 10 15 17 1 2 4
Similarly, head(practice, -1) refers to the entire vector except for the last element.
> head(practice, -1) [1] 1 2 10 15 17 1 2
If we separate them, we get a vector consisting of each element of the original vector divided by the element preceding it. We can separate these vectors directly because division is a vectorized operation.
> practice[-1] / head(practice, -1) [1] 2.0000 5.0000 1.5000 1.1333 0.0588 2.0000 2.0000 >
As in your example, we can subtract 1 at the end.
> practice[-1] / head(practice, -1) - 1 [1] 1.0000 4.0000 0.5000 0.1333 -0.9412 1.0000 1.0000
This applies to every element of the vector, since addition is also a vectorized operation in R.
No need for loops!
The equivalent loop code will be as follows:
x <- NULL for (i in 1:(length(practice) - 1)) { x[i] <- practice[i + 1] / practice[i] - 1 } x [1] 1.0000 4.0000 0.5000 0.1333 -0.9412 1.0000 1.0000
Although it also gives you what you want, it is obviously much longer. In fact, in many cases, the equivalent code loop is also much slower, because at each iteration the loops carry a lot of excess baggage around them. Thus, in addition to simplifying the code, vectorization often helps speed it up.