variables lose their labels after mutate() function is applied in R
07:51 06 Jul 2022

so assume some of my df columns have labels.

library(Hmisc)
df1 <- data.frame(a = c(0,1,2), b = c(0,1,2), d = c(0,1,2), e = c(0,1,2),
                  f= c("m","f","o"), output = c(0,1,2))
var_labs <- c(a = "aaa",
              b = "bbb",
              #d = "ddd",
              #e = "eee",
              f = "fff",
              output = "ooo")
label(df1) <- as.list(var_labs[match(names(df1), names(var_labs))])

enter image description here

When I apply mutate() functions on any column, that column loses its label.

library(dplyr)
df2 <- df1 %>%
   mutate_if(is.character,
             .funs = as.factor)

enter image description here

Is there a way to keep the labels after mutating?

r dplyr label mutation hmisc