How to Construct Vectors in R - dummies

How to Construct Vectors in R

By Andrie de Vries, Joris Meys

A vector is the simplest type of data structure in R. The R manual defines a vector as “a single entity consisting of a collection of things.” A collection of numbers, for example, is a numeric vector — the first five integer numbers form a numeric vector of length 5.

To construct a vector, type the following in the console:

> c(1,2,3,4,5)
[1] 1 2 3 4 5

In constructing your vector, you have successfully used a function in R. In programming language, a function is a piece of code that takes some inputs and does something specific with them. In constructing a vector, you tell the c() function to construct a vector with the first five integers. The entries inside the parentheses are referred to as arguments.

You also can construct a vector by using operators. An operator is a symbol you stick between two values to make a calculation. The symbols +, , *, and / are all operators, and they have the same meaning they do in mathematics. Thus, 1+2 in R returns the value 3, just as you’d expect.

One very handy operator is called sequence, and it looks like a colon (:). Type the following in your console:

> 1:5
[1] 1 2 3 4 5

That’s more like it. With three keystrokes, you’ve generated a vector with the values 1 through 5. Type the following in your console to calculate the sum of this vector:

> sum(1:5)
[1] 15