In R, you can perform element-wise comparisons on matrices using logical operators such as ==
, !=
, <
, <=
, >
, and >=
. These comparisons return a matrix of the same dimensions with logical values indicating the result of the comparison for each element.
In this example,
mat
.mat
with a scalar value 3
using the greater than operator >
.mat
is greater than 3
.comparison_result
.comparison_result
to the console to see the matrix of logical values.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
comparison_result <- mat > 3
print(comparison_result)
[,1] [,2] [,3] [1,] FALSE FALSE FALSE [2,] TRUE TRUE TRUE
In this example,
mat1
and mat2
.mat1
with the corresponding element in mat2
using the equality operator ==
.mat1
and mat2
are equal.comparison_result
.comparison_result
to the console to see the matrix of logical values.mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
mat2 <- matrix(c(1, 1, 3, 4, 4, 6), nrow = 2)
comparison_result <- mat1 == mat2
print(comparison_result)
[,1] [,2] [,3] [1,] TRUE FALSE TRUE [2,] TRUE FALSE TRUE
In this example,
mat
.mat
with a scalar value 4
using the less than or equal to operator <=
.mat
is less than or equal to 4
.comparison_result
.comparison_result
to the console to see the matrix of logical values.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
comparison_result <- mat <= 4
print(comparison_result)
[,1] [,2] [,3] [1,] TRUE TRUE TRUE [2,] TRUE FALSE FALSE
In this tutorial, we learned How to Perform Element-Wise Comparisons in R language with well detailed examples.