Home > Back-end >  Looping through labelles to create them in the same way
Looping through labelles to create them in the same way

Time:11-16

I really like the labelled package.

I have an analysis that has tons of labels that I need to make. Instead of adding them one by one, is there a way to have it loop through all columns and to modify them in the same way. For example, if I wanted to make them all Title Case. Please note, I'm hoping to change the label, not the actual column name.

library(labelled)
library(ggplot2)

mpg_new <- ggplot2::mpg %>% 
  set_variable_labels(manufacturer = "Manufacturer")

labelled::var_label(mpg_new$manufacturer)

CodePudding user response:

If we need to convert to title case on all of them, can pass a named vector as well in set_variable_labels

library(labelled)
library(ggplot2)
data(mpg)
var_labels <- setNames(tools::toTitleCase(names(mpg)), names(mpg))
mpg_new <- mpg %>%
    set_variable_labels(.labels = var_labels, .strict = FALSE)

-checking

> str(mpg_new)
tibble [234 × 11] (S3: tbl_df/tbl/data.frame)
 $ manufacturer: chr [1:234] "audi" "audi" "audi" "audi" ...
  ..- attr(*, "label")= chr "Manufacturer"
 $ model       : chr [1:234] "a4" "a4" "a4" "a4" ...
  ..- attr(*, "label")= chr "Model"
 $ displ       : num [1:234] 1.8 1.8 2 2 2.8 2.8 3.1 1.8 1.8 2 ...
  ..- attr(*, "label")= chr "Displ"
 $ year        : int [1:234] 1999 1999 2008 2008 1999 1999 2008 1999 1999 2008 ...
  ..- attr(*, "label")= chr "Year"
 $ cyl         : int [1:234] 4 4 4 4 6 6 6 4 4 4 ...
  ..- attr(*, "label")= chr "Cyl"
 $ trans       : chr [1:234] "auto(l5)" "manual(m5)" "manual(m6)" "auto(av)" ...
  ..- attr(*, "label")= chr "Trans"
 $ drv         : chr [1:234] "f" "f" "f" "f" ...
  ..- attr(*, "label")= chr "Drv"
 $ cty         : int [1:234] 18 21 20 21 16 18 18 18 16 20 ...
  ..- attr(*, "label")= chr "Cty"
 $ hwy         : int [1:234] 29 29 31 30 26 26 27 26 25 28 ...
  ..- attr(*, "label")= chr "Hwy"
 $ fl          : chr [1:234] "p" "p" "p" "p" ...
  ..- attr(*, "label")= chr "Fl"
 $ class       : chr [1:234] "compact" "compact" "compact" "compact" ...
  ..- attr(*, "label")= chr "Class"

CodePudding user response:

Another option to achieve your desired result would be via labelled::var_label like so:

library(labelled)
library(ggplot2)

mpg_new <- ggplot2::mpg

var_label(mpg_new) <- stringr::str_to_title(names(mpg_new))

var_label(mpg_new, unlist = TRUE)
#>   manufacturer          model          displ           year            cyl 
#> "Manufacturer"        "Model"        "Displ"         "Year"          "Cyl" 
#>          trans            drv            cty            hwy             fl 
#>        "Trans"          "Drv"          "Cty"          "Hwy"           "Fl" 
#>          class 
#>        "Class"
  • Related