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.
Method 1: Using unique()
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
# vector data a= c (1,2,3,4,1,2,5.9,9.0,9.0,45,78) # display vector print (a) # unique values 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
# vector data a= c ( "manoj" , "sravan" , "tripura" , "manoj" , "bala" , "sailaja" , "soundarya" , "sravan" ) # display vector print (a) # unique values print ( "Distinct values are :" ) print ( unique (a)) |
Output:
Example 3:
R
# vector data a= c ( FALSE , TRUE , FALSE , TRUE ) # display vector print (a) # unique values 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
# create a vector with numeric # elements x= c (1,2,3,4,5,6,7,8,1,2,3,4,5,3,4) # display a vector print (x) # get distinct value s using # duplicated function 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
# create a vector with character elements x= c ( "manoj" , "sravya" , "uha lakshmi" , "sravya" , "tapaswi" , "manoj" , "lakshmi" ) # display a vector print (x) # get distinct value s using duplicated # function print (x[! duplicated (x)]) |
Output:
Example 3:
R
# create a vector with elements x= c ( "manoj" , "sravya" , "uha lakshmi" , "sravya" , "tapaswi" , "manoj" , "lakshmi" , 1:20,12,34,56,23,11,7,8,9,0) # display a vector print (x) # get distinct value s using duplicated # function print (x[! duplicated (x)]) |
Output:
Please Login to comment...