Vectors in R Language

In R Language, a vector is the simplest data structure. A vector in R is also an object that contains elements having the same data type. To create a vector (say ‘x’) of the same type (say double) of elements consisting of five elements one can use c() function. For example,

Creating a vector in R using c() function

> x <- c(10, 7, 3, 2, 1)

The c() function can be used to combine a different number of vectors into a single vector. A single number is regarded as a vector of length one. For example, a vector (say ‘y’) is created by combing the existing vector(s) with a single number.

Appending a number to an existing vector(s)

One can append a number to an existing vector or even append a vector with another vector. For example,

> y <- c(x, .55)
> z <- c(x, y)

Extracting vector element(s)

The simplest example to select a particular element of a vector can be performed by using a subscription mechanism. That is, use the name of the vector with a square ([ ]) bracket with a number in it indicating the position of a vector element. For example,

> x[1]     # shows first element of vector  ‘x’
> x[1:2] # shows first two elements of vector ‘x’
> x[3:5] # shows elements of vector ‘x’ from index 3 to 5

Note that a positive number is used as a subscript index in square bracket. A positive subscript indicates the index (position) of a number to extract from the vector. A negative number as the index can also be used, which is used to select all the elements except the number(s) that are used in the square bracket ([ ]).

The example of a negative index is;

> x[-1]   # shows all elements of vector ‘x’ except first element
> x[-(1:2)] # shows elements of vector ‘x’ except first two elements

Also note that if subscripting number exceeds the number of elements in a vector, then it will result in NA (not available). For example,

> x[7]
> x[1:10]

Updating vector elements

One or more elements of a vector can be changed by the subscripting mechanism. For example, to change the 4th element of a vector, one can proceed as follow;

> x[4] <- 15   # 4th position of vector ‘x’ is updated to 15
> x[1:3] < – 4 # first three numbers are updated to 4
> x[1:3] <- c(1,2,3) # first three numbers are updated to 1, 2, and 3