w3resource

R Programming: Find Levels of Factor in a given Vector


Write a R program to find the levels of factor of a given vector.

Sample Solution :

R Programming Code :

# Create a vector 'v' with values including some repeated numbers and NA values
v = c(1, 2, 3, 3, 4, NA, 3, 2, 4, 5, NA, 5)

# Print a message indicating the display of the original vector
print("Original vector:")

# Print the contents of the vector 'v'
print(v)

# Print a message indicating the display of the factor levels of the vector
print("Levels of factor of the said vector:")

# Convert the vector 'v' into a factor and print the unique levels (ignoring NA values)
print(levels(factor(v)))

Output:

[1] "Original vector:"
 [1]  1  2  3  3  4 NA  3  2  4  5 NA  5
[1] "Levels of factor of the said vector:"
[1] "1" "2" "3" "4" "5"                         

Explanation:

  • v = c(1, 2, 3, 3, 4, NA, 3, 2, 4, 5, NA, 5):
    • Creates a vector v containing a series of numbers (1, 2, 3, etc.), including NA values, which represent missing data.
  • print("Original vector:"):
    • Prints the message "Original vector:" to indicate that the next output will display the contents of the vector v.
  • print(v):
    • Prints the contents of the vector v, which includes the numerical values and NA entries.
  • print("Levels of factor of the said vector:"):
    • Prints the message "Levels of factor of the said vector:" to indicate that the next output will show the factor levels of v.
  • print(levels(factor(v))):
    • Converts the vector v into a factor and prints the unique levels (distinct values) in v, ignoring NA. The factor() function categorizes the values, and levels() extracts and displays the unique levels of these values.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: R Programming Exercises Home.
Next: Write a R program to change the first level of a factor with another level of a given factor.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.