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 print(52L) #Logical type print(TRUE)
sol <- nchar("Counting number of  52  TRUE
Multiple Elements Vector
Using Colon operator with numeric data
This operator helps in a constant change over the numeric data with limits.
#Creating sequence a<- 4:10 b<-2.2:4.2 print(a) print(b)
 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!
R Programming for Beginners Video
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") 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)
 "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.
Vector Element Recycling
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 print(add.op)
 5 12 9 16
Check out the top R Programming Interview Questions to learn what is expected from R Programming professionals!
Vector Element Sorting
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) print(sort.sol) #sorting character vectors in decreasing order b <- c("Blue", "Red", "Green") revsort.sol <- sort(b, decreasing = TRUE) print(revsort.sol)
 -6 0 2 5  "Blue" "Green" "Red"