Vectors in R Language

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

Creating Vectors in R using the 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 combining 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, vectors in R Language can be appended like:

y <- c(x, .55)
z <- c(x, y)
Vectors in R Language

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,

# 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 a 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 ([ ]).

An 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 the 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 follows;

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

Learn about R Workspace, Objects, and .RData File

Online Multiple Choice Questions Quiz Preparation Website

Leave a Reply