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)
We need to assign and then return the column (
.x
). In addition, when there are more than one expression, wrap it inside the{}
-output