pivot_longer() with haven variable labels

155 Views Asked by At

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))
    )
  )
1

There are 1 best solutions below

0
Wimpel On

Here is a slightly different suggestion, not sure if it helps;

first rename the columns using an 'inverted' named vector.. then cast to long.

library(tidyverse)
temp <- unlist(var_label(tbl))
tbl %>%
  rename(all_of(setNames(names(temp), temp))) %>% 
  tidyr::pivot_longer(-id)