R Tutorial R Charts & Graphs R Statistics R References

R - exponent operator example



The example below show the usage of exponent(^) operator in different scenarios.

Exponent using scalar

If a vector or a matrix is raised to the power of a given scalar (single element atomic vector) , then each element of it is exponentiated.

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

#second operand
x2 <- 2

#using two scalars
print(x1 ^ x2)
#using a vector and a scalar
print(v1 ^ x2)
#using a matrix and a scalar
cat("\n")
print(m1 ^ x2)

The output of the above code will be:

[1] 100
[1] 100 400 900

     [,1] [,2] [,3]
[1,]  100  900 2500
[2,]  400 1600 3600

Exponent using vector

When a vector is raised to the power of another vector, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a matrix is divided by a vector, the length of longer object should be multiple of length of shorter object.

Please note that, When a matrix is raised to the power of a vector, elements are exponentiated 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(1, 2, 3)

#using a scalar (single element 
#atomic vector) and a vector
print(x1 ^ v2)
#using two vectors
print(v1 ^ v2)
#using a matrix and a vector
cat("\n")
print(m1 ^ v2)

The output of the above code will be:

[1]   10  100 1000
[1]    10   400 27000

     [,1]  [,2]   [,3]
[1,]   10 27000   2500
[2,]  400    40 216000

Exponent using matrix

When a matrix is raised to the power of another matrix, 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, 1, 2, 1, 2), nrow=2)

#using a scalar (single element 
#atomic vector) and a matrix
print(x1 ^ m2)
#using a vector and a matrix
cat("\n")
print(v1 ^ m2)
#using two matrices
cat("\n")
print(m1 ^ m2)

The output of the above code will be:

     [,1] [,2] [,3]
[1,]   10   10   10
[2,]  100  100  100

     [,1] [,2] [,3]
[1,]   10   30   20
[2,]  400  100  900

     [,1] [,2] [,3]
[1,]   10   30   50
[2,]  400 1600 3600

❮ R - Operators