R: Performing a calculation on a vector

I think I have a pretty simple question for R, but it's hard for me to find an example. Say I have a vector of numbers

practice<-c(1,2,10,15,17,1,2,4) 

and I want to calculate the change between numbers. The length of the vector is fixed at 36 observations. An example of what I want to calculate is ((2/1) -1), ((10 / 2-1), .... I am thinking of building a for loop, where I refer to a position and have a counter associated with this is.

+5
source share
1 answer

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 > # ^ ^ ^ ^ ^ ^ ^ > # 2/1 10/2 15/10 17/15 1/17 2/1 4/2 

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.

+5
source

Source: https://habr.com/ru/post/1215935/


All Articles