What are Vectors in R?
Vectors are the basic R data objects and there are 6 types of atomic vectors. They can be
- Integer,
- Logical,
- Double,
- Complex,
- Character and
- Raw
Creation of Vector in R
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 Vectors in R Programming
-
Using the 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
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 the number 1 position. A negative value in the index rejects that element from the 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"
Vector Manipulation in R
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!
The 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"