Package: labelled


Function: labelled()


1. Set labels for multiple variables (Var2 and Var3) with the same label values using a wide formatted data dictionary

Review the data (d5)

# A tibble: 3 x 3
  Var1   Var2  Var3
  <chr> <dbl> <dbl>
1 d         1    NA
2 e         2     2
3 f         1     1

Here I have a data dictionary that is formatted in wide format (which is more common in my work). So while I can’t necessarily pull the labels from a dictionary that is formatted this way, I can at least pull all variables that have the same labels, and label them at the same time, saving me time, especially if there are many variables with the same labels.

Review our data dictionary (dict_wide)

# A tibble: 3 x 3
  var   label              values         
  <chr> <chr>              <chr>          
1 Var1  ID                 a-z            
2 Var2  Do you like pizza? 1 = yes| 2 = no
3 Var3  Do you like pasta? 1 = yes| 2 = no

Pull our all variable names that are recoded as yes = 1 and 2 = no.

dict_yesno <- dict_wide %>%
  dplyr::filter(values == "1 = yes| 2 = no") %>%
  dplyr::pull(var)

Let’s see what variables were pulled

dict_yesno
[1] "Var2" "Var3"

Now we can apply our value labels to those variables using dplyr::across() and dplyr::all_of().

d5 <- d5 %>% 
  dplyr::mutate(dplyr::across(dplyr::all_of(dict_yesno), 
            ~labelled::labelled(., labels = 
                                  c("yes" = 1,
                                    "no" = 2))))

d5 %>% 
  labelled::val_labels()
$Var1
NULL

$Var2
yes  no 
  1   2 

$Var3
yes  no 
  1   2 

Go to Add value labels using long formatted data dictionary

Return to Label Data