In this article, we will test the equality of all vector elements in R programming language.
Method 1: Using variance
We can say that all vector elements are equal if the variance is zero. We can find variance by using the var() function
Syntax:
var(vector)==0
where vector is an input vector
This function returns true if all elements are the same, otherwise false.
Example: R program to check all elements in a vector equality
# consider a vector with same elements
vec1 = c(7, 7, 7, 7, 7, 7, 7)
print(var(vec1) == 0)
# consider a vector with different elements
vec2 = c(17, 27, 37, 47, 57, 7, 7)
print(var(vec2) == 0)
Output:
[1] TRUE [1] FALSE
Method 2: Using length() and unique() function
By using unique function if all the elements are the same then the length is 1 so by this way if the length is 1, we can say all elements in a vector are equal.
Syntax:
length(unique(vector))==1
- length() is used to find the length of unique vector
- unique() is used to get the unique values in a vector
If all elements are the same it returns true, otherwise false
Example: R program to test the equality of all elements in a vector
# consider a vector with same elements
vec1 = c(7, 7, 7, 7, 7, 7, 7)
print(length(unique(vec1)) == 1)
# consider a vector with different elements
vec2 = c(17, 27, 37, 47, 57, 7, 7)
print(length(unique(vec2)) == 1)
Output:
[1] TRUE [1] FALSE