What are Vectors?
Vectors are the basic R data objects and there are 6 types of the atomic vectors. They can be
- Character and
Creation of Vector
There are two types of vector creation:
- Single Element Vector
- Multiple Elements Vector
Go for this in-depth job-oriented R Programming Training Course now!
Single Element Vector
Whenever 1 word is written in R, it becomes a vector of length 1 and fits in one of the above vector types.
#Atomic vector of integer type
sol <- nchar("Counting number of
Multiple Elements Vector
Using Colon operator with numeric data
This operator helps in a constant change over the numeric data with limits.
 4 5 6 7 8 9 10
 2.2 3.2 4.2
Want to get certified in R Programming! Learn R from top R experts and excel in your career with Intellipaat’s R Programming certification!
Using sequence(Seq.) operator
#Creating vector by incrementing by 0.2
print(seq(2, 3, by = 0.2))
 2.0 2.2 2.4 2.6 2.8 3.0
Accessing Vector Elements
Indexing helps access the elements of a vector. The[ ] brackets are used for indexing.
Indexing starts with number 1 position. A negative value in the index rejects that element from output. 0 and 1 or TRUE and FALSE can be used for indexing.
#accessing vector elements
x<- c("letter one", "letter two", "letter three", "four", "five", "six")
#Usage of logical Index
d<- x[c(FALSE, FALSE,TRUE,TRUE,FALSE)]
#Using negative indexing
 "letter one" "letter three" "six"
 "letter three" "four"
 "five" "six"
Get familiar with the top R Programming Interview Questions to get a head start in your career!
Two vectors having the same length can do arithmetic operations such as addition, subtraction, multiplication, and division to get vector output.
When applying arithmetic operations to two vectors of unequal length, the elements of the shorter vector are recycled to complete the operations.
a <- c(2,4,6,8)
b <- c(3,8)
#b becomes c(3,8,3,8)
add.op <- a+b
 5 12 9 16
Check out the top R Programming Interview Questions to learn what is expected from R Programming professionals!
Sorting of elements in a vector takes place in ascending or descending order. It can be either numbers or characters.
a <- c(2, 5, -6, 0)
#sorting elements of vector
sort.sol <- sort(a)
#sorting character vectors in decreasing order
b <- c("Blue", "Red", "Green")
revsort.sol <- sort(b, decreasing = TRUE)
 -6 0 2 5
 "Blue" "Green" "Red"