logo

VECTOR


A vector is a variable which can store more than one value under the same variable.




Defining a vector

a=c(1,2,3,4,5,6,7,8,9,10)
a      # This will display the values stored in variable "a"
 [1]  1  2  3  4  5  6  7  8  9 10
sum(a) # This will give the total sum of all the elements of "a"
[1] 55
a^2  # This will square each and every elements of the vector "a"
 [1]   1   4   9  16  25  36  49  64  81 100
b=c(2,3,4,5,6,7,8,9,10,11)
a+b  # This will add corresponding elements of the two vectors "a" and "b" 
 [1]  3  5  7  9 11 13 15 17 19 21
b-a  # This will give the diffrence between corresponding elements of "b" and "a"
 [1] 1 1 1 1 1 1 1 1 1 1
a*b  # This will multiply corresponding elements of "a" and "b".
 [1]   2   6  12  20  30  42  56  72  90 110
a/b  # This will divide the elements of vector "a" by 
 [1] 0.5000000 0.6666667 0.7500000 0.8000000 0.8333333
 [6] 0.8571429 0.8750000 0.8888889 0.9000000 0.9090909
     # corresponding elements of vector "b".

Arranging a vector in increasing or decreasing order

aa=c(7,1,9,4,7,3,5,8,41,36,74,2)
sort(aa)
 [1]  1  2  3  4  5  7  7  8  9 36 41 74
sort(aa, decreasing = T)
 [1] 74 41 36  9  8  7  7  5  4  3  2  1

Some other in-built functions for vectors

The seq function is used to create a sequence of numbers

a_seq = seq(from=0, to= 10, by=1)
a_seq
 [1]  0  1  2  3  4  5  6  7  8  9 10

The rep function can be use to generate a vector with repeated value.

a_rep=rep(5, times=10)
a_rep
 [1] 5 5 5 5 5 5 5 5 5 5

Here a vector is created with the value 5 repeated 10 times.