How to Perform Multiple Calculations with Vectors Using R - dummies

How to Perform Multiple Calculations with Vectors Using R

By Andrie de Vries, Joris Meys

R is a vector-based language. You can think of a vector as a row or column of numbers or text. The list of numbers {1,2,3,4,5}, for example, could be a vector. Unlike most other programming languages, R allows you to apply functions to the whole vector in a single operation without the need for an explicit loop.

We’ll illustrate with some real R code. First, we’ll assign the values 1:5 to a vector that we’ll call x:

> x <- 1:5
> x
[1] 1 2 3 4 5

Next, we’ll add the value 2 to each element in the vector x and print the result:

> x + 2
[1] 3 4 5 6 7

You can also add one vector to another. To add the values 6:10 element-wise to x, you do the following:

> x + 6:10
[1] 7 9 11 13 15

To do this in most other programming language would require an explicit loop to run through each value of x.

This feature of R is extremely powerful because it lets you perform many operations in a single step. In programming languages that aren’t vectorized, you’d have to program a loop to achieve the same result.