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


February 25, 2023, Learn eTutorial
1516

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

For writing an R program to change the first level of a factor with another level of a given factor, we are using built-in functions levels(), factor().

The levels(), factor() functions in R compute the levels of factors of the vector in a single function.

  • factor() we can create a factor of the vector
  • 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)

  • x is an object, for example, a factor

factor(x = character(), levels, labels = levels,exclude = NA, ordered = is.ordered(x), nmax = NA)

  • x is a vector of data

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 and variable fa for finding the factor value of the vector. Finally, display the results.

ALGORITHM

STEP 1: Assign variable A with vector values

STEP 2: Display the real 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:")
print(A)
fa = factor(A)
print("Factor of the vector is:")
print(fa)
levels(fa)[1] = "e"
print(fa)
                                      

OUTPUT

[1] "Original vector is:"
[1] "a" "b" "a" "c" "b"
[1] "Factor of the vector is:"
[1] a b a c b
Levels: a b c
[1] e b e c b
Levels: e b c