R Program to find the levels of factor of a given vector

How to find the levels of a factor of a given vector

Here we are explaining how to write an R program to find the levels of a factor of a given vector. Here we are using built-in functions levels(factor()) for this calculation. The vector values are passed to these functions directly here. The levels(factor() function in R computes the levels of factors of the vector in a single function.

Using the function factor() we can create a factor of the vector and by using the level() function we can find levels of a factor. Factors are stored as integer vectors and which is closely related to vectors.

How levels of a factor of a given vector are calculated in R Program

Below are the steps used in the R program to find the levels of a factor of a given vector. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variable v for assigning vector values.

ALGORITHM

  • STEP 1 : Assign variable v with vector values
  • STEP 2 : Use the built-in functions
  • STEP 3 : First print original vector values
  • STEP 4 : levels(factor(v) with an argument as v to find levels of factors
  • STEP 5 : print the result of the function

R Source Code

v = c(1, 2, 3, 3, 4, NA, 3, 2, 4, 5, NA, 5)

print("The original vector is:")
## [1] "The original vector is:"
print(v)
##  [1]  1  2  3  3  4 NA  3  2  4  5 NA  5
print("Levels of factor of the vector:")
## [1] "Levels of factor of the vector:"
print(levels(factor(v)))
## [1] "1" "2" "3" "4" "5"