rtidyverser-labelled

Change multiple value labels using tidyverse syntax?


The labelled package provides this functionality to modify value labels for multiple variables in one go:

df <- data.frame(v1 = 1:3, v2 = c(2, 3, 1), v3 = 3:1)
val_labels(df[, c("v1", "v3")]) <- c(YES = 1, MAYBE = 2, NO = 3)
val_labels(df)

But I'm wondering if there's a way to do this in tidyverse syntax:

Something like this:

library(tidyverse)
df%>%
mutate(across(V1:V2), ~val_labels(.x)<-c(YES = 1, MAYBE = 2, NO = 3)

Solution

  • We need to assign and then return the column (.x). In addition, when there are more than one expression, wrap it inside the {}

    library(dplyr)
    library(labelled)
    df <- df %>%
      mutate(across(v1:v2, ~ 
           {
           val_labels(.x) <- c(YES = 1, MAYBE = 2, NO = 3)
           .x
         }))
    

    -output

    > val_labels(df)
    $v1
      YES MAYBE    NO 
        1     2     3 
    
    $v2
      YES MAYBE    NO 
        1     2     3 
    
    $v3
    NULL