Search code examples
rspsslabeling

Use sjlabelled::set_labels with lookup table


I need to label a values in a lot of variables with sjlabelled::set_labels. Here is a reproducable example and what already works:

library(data.table)
library(sjlabelled)

lookup <- data.table(id = paste0("q", 1:5),
                     answers = paste(paste0("atext", 1:5), paste0("btext", 1:5)
                                      , paste0("ctext", 1:5), sep = ";"))

data <- data.table(q1 = sample(1:3, 10, replace = TRUE),
                   q2 = sample(1:3, 10, replace = TRUE),
                   q3 = sample(1:3, 10, replace = TRUE),
                   q4 = sample(1:3, 10, replace = TRUE),
                   q5 = sample(1:3, 10, replace = TRUE))


data$q1 <- set_labels(data$q1, labels = unlist(strsplit(lookup[id == "q1", answers], split = ";")))

get_labels(data$q1)

So the labels for the different answers (=values) are seperated by a semicolon. I am able to make it work if I call the variables by id but as you can see in the example code but I am struggling with the task if I want to "loop" through all variables.

The goal is to be able to export the datatable (or dataframe) as an SPSS file. If it works with other packages I would also be happy.


Solution

  • Match the column names of data with id, split the answers on ; and pass the labels as a list.

    library(sjlabelled)
    
    data <- set_labels(data, labels = strsplit(lookup$answers[match(names(data), lookup$id)], ';'))
    get_labels(data)
    
    #$q1
    #[1] "atext1" "btext1" "ctext1"
    
    #$q2
    #[1] "atext2" "btext2" "ctext2"
    
    #$q3
    #[1] "atext3" "btext3" "ctext3"
    
    #$q4
    #[1] "atext4" "btext4" "ctext4"
    
    #$q5
    #[1] "atext5" "btext5" "ctext5"