R Programming: List the Distinct values in a Vector
R Programming: Vector Exercise-18 with Solution
Write a R program to list the distinct values in a vector from a given vector.
Sample Solution :
R Programming Code :
# Create a vector with some repeated values
v = c(10, 10, 10, 20, 30, 40, 40, 40, 50)
# Print the original vector
print("Original vector:")
print(v)
# Print the distinct (unique) values in the vector
print("Distinct values of the said vector:")
print(unique(v))
Output:
[1] "Original vector:" [1] 10 10 10 20 30 40 40 40 50 [1] "Distinct values of the said vector:" [1] 10 20 30 40 50
Explanation:
- v = c(10, 10, 10, 20, 30, 40, 40, 40, 50)
Creates a vector v with repeated values: 10, 20, 30, 40, and 50. - print("Original vector:")
Prints the label "Original vector:" to indicate the following output. - print(v)
Prints the content of vector v, which shows all the values including duplicates. - print("Distinct values of the said vector:")
Prints the label "Distinct values of the said vector:" to indicate the following output. - print(unique(v))
Prints the distinct values of the vector v, removing any duplicates and showing only unique values.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to extract every nth element of a given vector.
Next: Write a R program to find the elements of a given vector that are not in another given vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-18.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics