Get startedGet started for free

Vector manipulation

1. Vector manipulation

Now that you have seen how to create vectors, it is important to know how to do calculations with them. One of R's most powerful features is that its calculations are vectorized.

2. Vectors and friends

Let's go back to our original example of your friends Dan and Rob owing you money. If, instead of just one payment, they owed you 3 months of payments each, how could you write this using vectors? Hopefully, you would do something like this. With these vectors on hand, you can now ask the same question as before to know how they money they owe you together. The exact same code as before works great. To create a vector of monthly totals, just type dan + rob and assign this to monthly_total. The important thing to note here is that the operations on the vectors are done element-wise, one at a time. This means that 100 is added to 50, 200 to 75, and 150 to 100. Looking at monthly_total confirms this. To know how much they owe you altogether, you would have to add up each element of the total_monthly vector. The function sum can do this for you.

3. More examples

Just to get a feel for the concept, here are a few other examples of vector calculations. As you can see, two vectors of the same length are operated on, and a vector of the same size is returned. Even when you multiply a vector of length 3 by a single number, remember that the single number is actually a vector of length one. In this case, R does something behind the scenes called "recycling", where it reuses the single number three times to create a vector of length 3, then does element-wise arithmetic on the two vectors.

4. Let's practice!

Don't worry if this seems a bit tricky at first. You'll have plenty of practice in the exercises. Enjoy!