I need to label a lot of variables with sjlabelled::set_label. Here is a reproducable example and what already works:
library(data.table)
library(sjlabelled)
lookup <- data.table(id = paste0("q", 1:5),
question = paste0("qtext", 1:5))
data <- data.table(q1 = sample(1:5, 10, replace = TRUE),
q2 = sample(1:5, 10, replace = TRUE),
q3 = sample(1:5, 10, replace = TRUE),
q4 = sample(1:5, 10, replace = TRUE),
q5 = sample(1:5, 10, replace = TRUE))
data[, q1 := set_label(data[, q1], lookup[id == "q1", question])]
get_label(data$q1)
So I am able to label specific variables if I call them with their id but I am struggling with the task if I want to "loop" through all variables. Tried with a for loop with no success.
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.
You can use set_label
directly on a dataframe.
library(sjlabelled)
data <- set_label(data, lookup$question[match(names(data), lookup$id)])
get_label(data)
# q1 q2 q3 q4 q5
#"qtext1" "qtext2" "qtext3" "qtext4" "qtext5"