relevel
The relevel
function is used to modify the factor levels in R.
Syntax:
relevel(x, ref)
Parameters:
x
: A factor indicating the factor whose levels need to be modified.ref
: A character string indicating the new reference level.
Explanation:
The relevel
function changes the reference level of a factor. The reference level is used as a base level for comparisons and contrasts in statistical modeling in R. By default, R sets the first level of a factor as the reference level. However, in some cases, it is useful to change this reference level to another level for better interpretation of results.
Example:
Let’s consider a factor variable grade
which represents students’ grades: A, B, C, and D. By default, the reference level is set to A. We can use the relevel
function to change the reference level to D.
# Create a factor variable
grade <- factor(c("A", "B", "C", "D", "B", "D", "A", "C"))
# Print the levels before relevel
levels(grade)
# Change the reference level to D
grade <- relevel(grade, ref = "D")
# Print the levels after relevel
levels(grade)
The output will be:
[1] "A" "B" "C" "D"
[1] "D" "A" "B" "C"
After using the relevel
function, the new reference level is set to D, and the levels of the factor are rearranged accordingly.