Skip to contents

Rename the levels of a categorical variables, and returns the result along with tidyverse code used to generate it.

Usage

rename_levels(data, var, tobe_asis, name = NULL)

Arguments

data

a dataframe with the column to be renamed

var

a character of the categorical variable to rename

tobe_asis

a named list of the old level names assigned to the new level names ie. list('new level names' = 'old level names')

name

a name for the new variable

Value

original dataframe containing a new column of the renamed categorical variable with tidyverse code attached

See also

Author

Zhaoming Su

Examples

renamed <- rename_levels(iris,
    var = "Species",
    tobe_asis = list(set = "setosa", ver = "versicolor")
)
cat(code(renamed))
#> iris |> dplyr::mutate(Species.renamed = forcats::fct_recode(Species, set = "setosa",   ver = "versicolor"), .after = Species)
head(renamed)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Species.renamed
#> 1          5.1         3.5          1.4         0.2  setosa             set
#> 2          4.9         3.0          1.4         0.2  setosa             set
#> 3          4.7         3.2          1.3         0.2  setosa             set
#> 4          4.6         3.1          1.5         0.2  setosa             set
#> 5          5.0         3.6          1.4         0.2  setosa             set
#> 6          5.4         3.9          1.7         0.4  setosa             set