R - equal operator example
The example below shows the usage of equal(==) operator in different scenarios.
Comparing with a scalar
If a vector or a matrix is compared with a scalar (single element atomic vector), it acts on each element of it and returns TRUE if the element is equal to the scalar, else returns FALSE.
#first operand x1 <- 10 v1 <- c(10, 20, 10) m1 <- matrix(c(10, 20, 30, 40, 50, 10), nrow=2) #second operand x2 <- 10 #comparing two scalars print(x1 == x2) #comparing a vector with a scalar print(v1 == x2) #comparing a matrix with a scalar cat("\n") print(m1 == x2)
The output of the above code will be:
[1] TRUE [1] TRUE FALSE TRUE [,1] [,2] [,3] [1,] TRUE FALSE FALSE [2,] FALSE FALSE TRUE
Comparing with a vector
When two vectors are compared, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a vector is compared with a matrix, the length of longer object should be multiple of length of shorter object.
Please note that, When a vector is compared with a matrix, elements are compared column-wise.
#first operand x1 <- 10 v1 <- c(10, 20, 10) m1 <- matrix(c(10, 20, 30, 40, 50, 10), nrow=2) #second operand v2 <- c(10, 20, 30) #comparing a scalar (single element #atomic vector) with a vector print(x1 == v2) #comparing two vectors print(v1 == v2) #comparing a matrix with a vector cat("\n") print(m1 == v2)
The output of the above code will be:
[1] TRUE FALSE FALSE [1] TRUE TRUE FALSE [,1] [,2] [,3] [1,] TRUE TRUE FALSE [2,] TRUE FALSE FALSE
Comparing with a matrix
When two matrices are compared, 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, 10) m1 <- matrix(c(10, 20, 30, 40, 50, 10), nrow=2) #second operand m2 <- matrix(c(10, 20, 30, 10, 20, 30), nrow=2) #comparing a scalar (single element #atomic vector) with a matrix print(x1 == m2) #comparing a vector with a matrix cat("\n") print(v1 == m2) #comparing two matrices cat("\n") print(m1 == m2)
The output of the above code will be:
[,1] [,2] [,3] [1,] TRUE FALSE FALSE [2,] FALSE TRUE FALSE [,1] [,2] [,3] [1,] TRUE FALSE TRUE [2,] TRUE TRUE FALSE [,1] [,2] [,3] [1,] TRUE TRUE FALSE [2,] TRUE FALSE FALSE
❮ R - Operators