What are Vectors?
Vectors are the basic R data objects and there are 6 types of the atomic vectors. They can be
- Integer,
- Logical,
- Double,
- Complex,
- Character and
- Raw
Creation of Vector
There are two types of vector creation:
- Single Element Vector
- Multiple Elements Vector
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
print(52L)
#Logical type
print(TRUE)
Output:
sol <- nchar("Counting number of
[1] 52Â Â Â Â Â
[1] TRUE

Multiple Elements Vector
-
Using Colon operator with numeric data
This operator helps in a constant change over the numeric data with limits.
Example:
#Creating sequence
a<- 4:10
b<-2.2:4.2
print(a)
print(b)
Output:
[1] 4 5 6 7 8 9 10
[1] 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 Data Science certification!
Using sequence(Seq.) operator
#Creating vector by incrementing by 0.2
print(seq(2, 3, by = 0.2))
Output:
[1]Â 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")
b<- x[c(1,3,6)]
print(b)
#Usage of  logical Index
d<- x[c(FALSE, FALSE,TRUE,TRUE,FALSE)]
print(d)
#Using negative indexing
e<- x[c(-1,-2,-3,-4)]
print(e)
Output:
[1] "letter one" "letter three" "six"
[1] "letter three" "four"
[1] "five" "six"
Get familiar with the top R Interview Questions to get a head start in your career!
Vector Manipulation
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.
Example:
a <- c(2,4,6,8)
b <- c(3,8)
#b becomes c(3,8,3,8)
add.op <- a+b
print(add.op)
 Output:
[1]Â 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.
Example:
a <- c(2, 5, -6, 0)
#sorting elements of vector
sort.sol <- sort(a)
print(sort.sol)
Â
#sorting character vectors in decreasing order
b <- c("Blue", "Red", "Green")
revsort.sol <- sort(b, decreasing = TRUE)
print(revsort.sol)Â
Output:
[1] -6 0 2 5
[1] "Blue" "Green" "Red"