R Program to change the first level of a factor with another level of a given factor

How to change the first level of a factor with another level of a given factor

Here we are explaining how to write an R program to change the first level of a factor with another level of a given factor. Here we are using built-in functions levels(),factor() for this conversion. The vector values are passed to these functions directly here. The levels(), factor() functions 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. The syntax of these functions are

levels(x) #where x is an object, for example, a factor factor(x = character(), levels, labels = levels,exclude = NA, ordered = is.ordered(x), nmax = NA)

– Where x is a vector of data, usually taking a small number of distinct values

How to change the first level of a factor with another level of a factor in the 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 A for assigning vector values variable fa for finding the factor value of the vector

ALGORITHM

  • STEP 1: Assign variable A with vector values
  • STEP 2: First print original vector values
  • STEP 3:Call the built-in function factor as fa = factor(A)
  • STEP 4: Print the factor of the vector
  • STEP 6:Call the built-in function levels as levels(fa)[1] = “e”
  • STEP 7: print the variable fa

R Source Code

A = c("a", "b", "a", "c", "b")

print("Original vector is:")
## [1] "Original vector is:"
print(A)
## [1] "a" "b" "a" "c" "b"
fa = factor(A)

print("Factor of the vector is:")
## [1] "Factor of the vector is:"
print(fa)
## [1] a b a c b
## Levels: a b c
levels(fa)[1] = "e"

print(fa)
## [1] e b e c b
## Levels: e b c