I have a tibble whose columns are labelled using haven, like so:
library(tibble)
library(tidyr)
library(labelled)
tibble(
id = 101:102,
var_1 = c(1, 2),
var_2 = c(3, 4)
) %>%
set_variable_labels(var_1 = "Variable 1", var_2 = "Variable 2") -> tbl
I would like to pivot_longer() var_1 and var_2 but would like its variable labels rather than its variable names to end up in the name column. Is there a way to do this that's less clunky than
tbl |>
tidyr::pivot_longer(-id) |>
mutate(
name = forcats::fct_recode(
name,
# flip the name -> label mapping
!!!setNames(names(var_label(tbl)), var_label(tbl))
)
)
Here is a slightly different suggestion, not sure if it helps;
first rename the columns using an 'inverted' named vector.. then cast to long.