user3549613
user3549613

Reputation: 71

R: Performing a Calculation on a Vector

I think I have a pretty basic question for R but am having trouble finding 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. Example of what I want to calculate is ((2/1)-1),((10/2-1),.... I am thinking of building a for loop where I reference the position and have a counter associated with it.

Upvotes: 5

Views: 490

Answers (1)

Alex A.
Alex A.

Reputation: 5586

One of the benefits of using R is its vectorization, which means that it can easily perform operations on an entire vector at once rather than having to loop through each element.

As David Arenburg mentioned in a comment (with updates thanks to BondedDust and Dominic Comtois), you can in your case do this:

practice[-1] / head(practice, -1) - 1

What does this do?

practice[-1] references the entire vector except the first element.

> practice[-1]
[1] 2 10 15 17 1 2 4

Similarly, head(practice, -1) references the entire vector except the last element.

> head(practice, -1)
[1] 1 2 10 15 17 1 2

If we divide these, we get a vector consisting of each element in the original vector divided by the element that precedes it. We can divide 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 you have 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 is applied to each element in the vector since addition is also a vectorized operation in R.

No loops necessary!

The equivalent loop code would be this:

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

While that also gets you what you want, it's obviously a lot longer. In fact, in many cases equivalent loop code is significantly slower too, since loops carry around a lot of extra baggage at each iteration. So besides simplifying your code, vectorization will often help speed it up too.

Upvotes: 5

Related Questions