Vectorization

A vectorized function works not just on a single value, but on a whole vector of values at the same time. Many operations in R are vectorized. It means that operations occur in parallel in certain R objects. This allows you to write code that is efficient, concise, and easier to read than in non-vectorized languages. Following example shows how vectorized operation works in R.

 

x<- 10:20
y<-4
z<- x+y
print(z)
y*x
y^x
sqrt(x)
log(x)

Output:

> print(z)
[1] 14 15 16 17 18 19 20 21 22 23 24
> y*x
[1] 40 44 48 52 56 60 64 68 72 76 80
> y^x
[1] 1.048576e+06 4.194304e+06 1.677722e+07 6.710886e+07 2.684355e+08 1.073742e+09 4.294967e+09 1.717987e+10 6.871948e+10 2.748779e+11
[11] 1.099512e+12
> sqrt(x)
[1] 3.162278 3.316625 3.464102 3.605551 3.741657 3.872983 4.000000 4.123106 4.242641 4.358899 4.472136
> log(x)
[1] 2.302585 2.397895 2.484907 2.564949 2.639057 2.708050 2.772589 2.833213 2.890372 2.944439 2.995732

 

If you do not want to use vectorization, then for doing the addition you have to write a code like this.

 

m <- numeric(length(x))
for(i in seq_along(x)) {
m <- x[i] + y
print(m)
}

m

Output:

[1] 14
[1] 15
[1] 16
[1] 17
[1] 18
[1] 19
[1] 20
[1] 21
[1] 22
[1] 23
[1] 24

Now you have understood the power of vectorized operations in R. similarly, another thing you can do in a vectorized manner is logical comparisons. So suppose you wanted to know which elements of a vector were greater than equals 10 or not. You could do following way.

 

x<-6:15
x>=10

Output:

[1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

 

x==10
x<=10

Output:

> x==10
[1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
> x<=10
[1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE

Vectorized Matrix Operations:

Matrix operations are also vectorized. This way, we can do element-by-element operations on matrices without having to loop over every element. Some matrix operations examples had shown in matrix section

 

x <- matrix(1:4, 2, 2)
y <- matrix(rep(10, 4), 2, 2)
#Element-wise Addition
x+y
#Element-wise Substraction
y-x
#Element-wise multiplication
x*y
#Element-wise Division
y/x
#True matrix multiplication
x %*% y

Output:

> #Element-wise Addition
> x+y
[,1] [,2]
[1,] 11 13
[2,] 12 14
> #Element-wise Substraction
> y-x
[,1] [,2]
[1,] 9 7
[2,] 8 6
> #Element-wise multiplication
> x*y
[,1] [,2]
[1,] 10 30
[2,] 20 40
> #Element-wise Division
> y/x
[,1] [,2]
[1,] 10 3.333333
[2,] 5 2.500000
> #True matrix multiplication
> x %*% y
[,1] [,2]
[1,] 40 40
[2,] 60 60

R – Operators

Dates and Times