Assign variable labels in loop

815 views Asked by At

I've got a big old dataset that I would like to programmatically label. To do so I've used the look_for() function from the labelled package to create a df of variables and labels, which I want to loop through to assign labels to my variables. Below is a simple example:

library(labelled)
# create table of vars and add some labels
vlabels <- labelled::look_for(mtcars) %>%
  mutate(label = paste0("label for ", variable))

vlabels contents:

> vlabels
 pos variable label          col_type values
 1   mpg      label for mpg  dbl            
 2   cyl      label for cyl  dbl            
 3   disp     label for disp dbl            
 4   hp       label for hp   dbl            
 5   drat     label for drat dbl            
 6   wt       label for wt   dbl            
 7   qsec     label for qsec dbl

Attempt to assign labels:

for(v in length(vlabels$variable)){
  var = vlabels$variable[v]
  vlabel = vlabels$label[v]
  attr(mtcars[var], 'label') <- vlabel
}

Checking output and my labels do not appear:

attr(mtcars$mpg, 'label') 
> attr(mtcars$mpg, 'label')
NULL

Not sure what I'm missing here except that loops are bad and I should use apply. Thanks!

1

There are 1 answers

3
Waldi On

You could use var_label:

library(labelled)

var_label(mtcars) <- paste0("label for ", colnames(mtcars))
var_label(mtcars)

$mpg
[1] "label for mpg"

$cyl
[1] "label for cyl"

$disp
[1] "label for disp"
...

You can also assign labels for each column individually:

var_label(mtcars$mpg) <- "Specific label for mpg"
var_label(mtcars)

var_label(mtcars)
$mpg
[1] "Specific label for mpg"

$cyl
NULL

$disp
NULL
...

Which leads with your original loop to:

for(v in 1:length(vlabels$variable)){
  var = vlabels$variable[v]
  vlabel = vlabels$label[v]
  var_label(mtcars[[var]])<-vlabel
}

var_label(mtcars)
$mpg
[1] "label for mpg"

$cyl
[1] "label for cyl"

$disp
[1] "label for disp"
...