R Vectors

A vector represents a set of elements of the same mode which can be integer, floating number, character, complex and so on. It is a basic data object in R in which a single number is also considered as one element vector instead of calling scalar vector.

Creating a Vector

These are the following ways to create a vector -

Create a vector using concatenation function c

The concatenation function c is used to create a vector that binds the element together of the same type.

Here, a vector contains four numeric values

x <- c(3, 5, 2, 5)

and here, a vector contains four character strings

y <- c("dog", "cat", "rat", "fox")

and the example below contains a vector of four logical values.

z <- c(TRUE, FASLE, FALSE, TRUE)

Create a sequential vector

R provides seq() function to generate a vector of sequence of numbers.

The below code generates a vector of sequence beginning from 1 to 5 and each next element increment by 0.3.

seq(1, 5, by=0.3)
[1] 1.0 1.3 1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4.0 4.3 4.6 4.9

Create a vector using a colon (:)

The colon operator generates a regular sequence of numbers. It requires starting and end value of the sequence. The below example generates a sequence of 1 to 5.

x <- 1:5
print(x)
[1] 1 2 3 4 5





Access Element of Vector

A vector element can be accessed by the vector index. It starts with index 1 unlike in other programming language element starts with 0 index. We can use the [ ] brackets for indexing.

The below example accesses second vector element.

x <- c(3, 5, 2, 5)
x
[1] 3 5 2 5
x[2]
[1] 5

Get Length of a Vector

R provides length() function to return the length of a vector.

x <- c(3, 5, 2, 5)
length(x)
[1] 4

Delete a Vector

To delete a vector element, simply assign it to a null value.

x <- c(3, 5, 2, 5)
x <- NULL
x
NULL




Modify a vector element

To modify a vector element, simply assign the element index with new value with the help of assignment operator. In the below example, we modify the third vector element.

x <- c(3, 5, 2, 5)
x[3] <- 9;
x
NULL

Arithmetic operations on vector

We can perform arithmetic operations on vectors of both equal and unequal length. In case of unequal length vector, the shorter length vector is recycled to complete the operation.

Arithmetic operations of equal length vectors

x1 <- c(2,3,5,2,7,2)
x2 <- c(6,7,4,1,7,2)
a <- x1+x2
print(a)

s <- x1-x2
print(s)

m <- x1*x2
print(m)

d <- x1/x2
print(d)

Arithmetic operations of unequal length vectors

x1 <- c(6,8,5,6,7,2)
x2 <- c(3,5)
a <- x1+x2
print(a)

s <- x1-x2
print(s)

m <- x1*x2
print(m)

d <- x1/x2
print(d)