List distinct values in a vector in R
In this article, we will discuss how to display distinct values in a vector in R Programming Language.
For this, the vector from which distinct elements are to be extracted is passed to the unique() function. The result will give all distinct values in a vector.
Syntax:
unique(vector_name)
Where, vector_name is the input vector.
Example 1:
R
a= c (1,2,3,4,1,2,5.9,9.0,9.0,45,78)
print (a)
print ( unique (a))
|
Output:
[1] 1.0 2.0 3.0 4.0 1.0 2.0 5.9 9.0 9.0 45.0 78.0
[1] 1.0 2.0 3.0 4.0 5.9 9.0 45.0 78.0
Example 2:
R
a= c ( "manoj" , "sravan" , "tripura" , "manoj" ,
"bala" , "sailaja" , "soundarya" , "sravan" )
print (a)
print ( "Distinct values are :" )
print ( unique (a))
|
Output:
Example 3:
R
a= c ( FALSE , TRUE , FALSE , TRUE )
print (a)
print ( "Distinct values are :" )
print ( unique (a))
|
Output:
Method 2: Using duplicated()
By using this method we can get duplicate values. So, if we want to get unique values, we can implement this function along with ! Operator. This will do exactly the reverse of the duplicated() function.
Syntax:
!duplicated(vector_data)
This will return boolean values.
In order to return actual values, we can use index operator — []
Syntax:
vector_name[!duplicated(vector_name)]
Example 1:
R
x= c (1,2,3,4,5,6,7,8,1,2,3,4,5,3,4)
print (x)
print (x[! duplicated (x)])
|
Output:
[1] 1 2 3 4 5 6 7 8 1 2 3 4 5 3 4
[1] 1 2 3 4 5 6 7 8
Example 2:
R
x= c ( "manoj" , "sravya" , "uha lakshmi" , "sravya" ,
"tapaswi" , "manoj" , "lakshmi" )
print (x)
print (x[! duplicated (x)])
|
Output:
Example 3:
R
x= c ( "manoj" , "sravya" , "uha lakshmi" ,
"sravya" , "tapaswi" , "manoj" , "lakshmi" ,
1:20,12,34,56,23,11,7,8,9,0)
print (x)
print (x[! duplicated (x)])
|
Output:
Last Updated :
31 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...