Renaming categorical variables and their levels, for instance for summary tables, can be fiddly. This function accepts tibbles containing the old and new names for arguments and levels, and returns a dataframe (or list of dataframes, if one is passed) with variables and levels renamed.
rename_cat_variables(data, var_names = NULL, level_names = NULL)
A dataframe or list of dataframes (e.g., from multiple imputation) contains the variables. If a list is passed, it must have class "list"
A tibble containing old
and new
names for the variables. If NULL, only levels are renamed.
A tibble containing old var
names and level_old
and level_new
names. If NULL, only variables are renamed.
The dataframe or list of dataframes passed to data, with variables and/or levels renamed. Any variables where levels are renamed will be converted to factors.
var_renames <- tibble::tribble(
~old, ~new,
"gndr", "Gender",
"cntry", "Country"
)
level_renames <- tibble::tribble(
~var, ~level_old, ~level_new,
"gndr", "1", "Male",
"gndr", "2", "Female",
"cntry", "DE", "Germany",
"cntry", "FR", "France",
"cntry", "GB", "UK"
)
rename_cat_variables(ess_health, var_names = var_renames,
level_names = level_renames)
#> # A tibble: 7,226 × 23
#> Country Gender agea eisced pweight pspwght health height weight icbrnct
#> <fct> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 Germany Male 52 3 2.30 0.608 1 187 78 1
#> 2 Germany Female 52 5 2.30 0.463 2 168 110 1
#> 3 Germany Male 62 5 2.30 0.640 1 181 84 1
#> 4 Germany Female 62 3 2.30 1.14 3 155 63 1
#> 5 Germany Female 20 5 2.30 0.853 1 160 70 1
#> 6 Germany Male 49 7 2.30 0.364 2 177 89 1
#> 7 Germany Male 63 6 2.30 0.310 3 169 87 1
#> 8 Germany Female 32 3 2.30 1.35 3 163 62 1
#> 9 Germany Female 66 5 2.30 0.341 1 157 56 1
#> 10 Germany Male 15 1 2.30 1.74 3 172 72 1
#> # ℹ 7,216 more rows
#> # ℹ 13 more variables: etfruit <dbl>, eatveg <dbl>, dosprt <dbl>,
#> # cgtsmke <dbl>, alcfreq <dbl>, fltdpr <dbl>, flteeff <dbl>, slprl <dbl>,
#> # wrhpp <dbl>, fltlnl <dbl>, enjlf <dbl>, fltsd <dbl>, cldgng <dbl>