fct_relevel
In this document, I will introduce the fct_relevel function and show what it’s used for.
fct_relevel is part of the forcats R package.
I will be using
icu_Hoda_edited
dataset adapted from 513 BSTA class.
tabyl (icu_Hoda_edited$race)
## icu_Hoda_edited$race n percent
## Black 15 0.075
## Other 10 0.050
## White 175 0.875
class(icu_Hoda_edited$race)
## [1] "character"
I factorize it then check for its levels.
icu_Hoda_edited <-icu_Hoda_edited%>% mutate(race= factor(race))
class(icu_Hoda_edited$race)
## [1] "factor"
levels(icu_Hoda_edited$race)
## [1] "Black" "Other" "White"
The function simply is used to reorder factor levels by hand when we want to specify the reference level.
(e.g. when plotting, or when performing a regression analysis)
If we want to make comparisons relative to “White” race, we need to move it to the front by using fct_relevel().
icu_Hoda_edited <- icu_Hoda_edited%>%
mutate(race = race %>%
fct_relevel("White"))
levels(icu_Hoda_edited$race)
## [1] "White" "Black" "Other"
icu_Hoda_edited <- icu_Hoda_edited%>%
mutate(race = race %>%
fct_relevel("White","Other"))
levels(icu_Hoda_edited$race)
## [1] "White" "Other" "Black"
race_factor <- factor(race_character,levels = c(“White”, “Other”, “Black”))
Useful when creating a factor.
May not be helpful if we have a lot of levels because we will need to write them all down - long code!
race_factor<-relevel(race_factor, ref=“White”)
YES! fct_relevel is useful if we want to reorder the levels in a factor to specify the reference level.
Helps us “pull” a level (or more) to the front relative to all other levels. The rest of the levels remain unchanged and follow according to their alphabetical order.
Source: R for Health Data Science Ewen Harrison and Riinu Pius 2021-01-15 https://argoshare.is.ed.ac.uk/healthyr_book/chap08-h2-fct-relevel.html