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!
You could use
var_label
:You can also assign labels for each column individually:
Which leads with your original loop to: