Test for Equality of All Vector Elements in R
Last Updated :
23 Sep, 2021
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
R
vec1 = c (7, 7, 7, 7, 7, 7, 7)
print ( var (vec1) == 0)
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
R
vec1 = c (7, 7, 7, 7, 7, 7, 7)
print ( length ( unique (vec1)) == 1)
vec2 = c (17, 27, 37, 47, 57, 7, 7)
print ( length ( unique (vec2)) == 1)
|
Output:
[1] TRUE
[1] FALSE
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...