R Program to list the distinct values from a given vector


February 21, 2023, Learn eTutorial
963

How to list the distinct values from a given vector using R program?

To write an R program to list the distinct values from a given vector, we are using a built-in function unique(). This function helps to find the distinct or unique values from the vector by eliminating duplicate values. The syntax of this function is 

unique(x)

  • Here x is the vector, matrix, or data frame, returns a similar object whose duplicate elements need to be eliminated.

In this R program, we are passing the values to the function directly. For that first, we consider the variable A in which vector value is assigned. Finally, call the unique function as unique(A) for finding the distinct element.

ALGORITHM

STEP 1: Assign variable A with vector values

STEP 2: First print original vector values

STEP 3: Call the function unique as unique(A)

STEP 5: print the result of the function

R Source Code

                                          A = c(25, 25, 10, 15, 20, 20, 30, 40)
print("Original vector:")
print(A)
print("Distinct values of the vector:")
print(unique(A))
                                      

OUTPUT

[1] "Original vector:"
[1] 25, 25, 10, 15, 20, 20, 30, 40)
[1] "Distinct values of the vector:"
[1] 10 15 20 25 30 40