R Tutorial R Charts & Graphs R Statistics R References

R - multiplication operator example



The example below shows the usage of multiplication(*) operator in different scenarios.

Multiplying by a scalar

If a scalar (single element atomic vector) is multiplied to a vector or a matrix, it is multiplied to each element of the vector or matrix.

#first operand
x1 <- 10
v1 <- c(10, 20, 30)
m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2)

#second operand
x2 <- 5

#multiplying two scalars
print(x1 * x2)
#multiplying a vector by a scalar
print(v1 * x2)
#multiplying a matrix by a scalar
cat("\n")
print(m1 * x2)

The output of the above code will be:

[1] 50
[1]  50 100 150

     [,1] [,2] [,3]
[1,]   50  150  250
[2,]  100  200  300

Multiplying by a vector

When two vectors are multiplied, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a vector is multiplied to a matrix, the length of longer object should be multiple of length of shorter object.

Please note that, When a vector is multiplied to a matrix, elements are multiplied column-wise.

#first operand
x1 <- 10
v1 <- c(10, 20, 30)
m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2)

#second operand
v2 <- c(5, 6, 7)

#multiplying a scalar (single element 
#atomic vector) by a vector
print(x1 * v2)
#multiplying two vectors
print(v1 * v2)
#multiplying a matrix by a vector
cat("\n")
print(m1 * v2)

The output of the above code will be:

[1] 50 60 70
[1]  50 120 210

     [,1] [,2] [,3]
[1,]   50  210  300
[2,]  120  200  420

Multiplying by a matrix

When two matrices are multiplied, their dimension should be same or dimension of bigger matrix should be multiple of dimension of smaller matrix.

#first operand
x1 <- 10
v1 <- c(10, 20, 30)
m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2)

#second operand
m2 <- matrix(c(1, 2, 3, 4, 5, 6), nrow=2)

#multiplying a scalar (single element 
#atomic vector) by a matrix
print(x1 * m2)
#multiplying a vector by a matrix
cat("\n")
print(v1 * m2)
#multiplying two matrices
cat("\n")
print(m1 * m2)

The output of the above code will be:

     [,1] [,2] [,3]
[1,]   10   30   50
[2,]   20   40   60

     [,1] [,2] [,3]
[1,]   10   90  100
[2,]   40   40  180

     [,1] [,2] [,3]
[1,]   10   90  250
[2,]   40  160  360

❮ R - Operators