strengejacke / sjlabelled

Working with Labelled Data in R

Home Page:https://strengejacke.github.io/sjlabelled

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rename a dataframe using labels

onesandzeroes opened this issue · comments

When working with functions/packages that don't support labels, it can be useful to set a dataframe's column names using the variable labels. E.g. the default plot() method for dataframes doesn't support dataframes, it will only show the column names by default.

I've written a rename_from_labels function that applies the variable labels to the dataframe column names, happy to work on a PR (including tests and documentation) if you think this would be useful and fit in the package.

Example:

library(sjlabelled)
library(dplyr)

rename_from_labels <- function(x) {
    labs <- sjlabelled::get_label(x)
    # Ignore variables without labels
    labs <- labs[labs != ""]
    new_names <- unname(labs)
    old_names <- names(labs)
    replace_vec <- setNames(old_names, new_names)
    dplyr::rename(x, !!! replace_vec)
}

data(iris)

iris <- iris %>%
    var_labels(
        Petal.Length = "Petal length (cm)",
        Petal.Width = "Petal width (cm)"
    )

# Show the variable names in the plot
iris %>%
    rename_from_labels() %>%
    plot()

Created on 2020-01-14 by the reprex package (v0.3.0)

Thanks, I added a quick implementation, which is actually just a small wrapper:
https://github.com/strengejacke/sjlabelled/blob/master/R/label_to_colnames.R