I would like to create a function that updates a data frame from a different environment. Specifically, I would like to update the labels of a data frame using the Hmisc::label() function.
assign_label <- function(df, col) {
col <- rlang::as_name(rlang::ensym(col))
Hmisc::label(df[,col]) <- fetch_label(col)
}
fetch_label <- function(col) {
val <- c("mpg" = "MPG",
"hp" = "HP")
unname(val[col])
}
The following code executes without issue: assign_label(mtcars, hp)
However, it does not actually alter the data frame in the calling environment. I just can't figure out how to make it do what I imagine.
Ideally, I would like to be able to pipe a dataframe to this function as such:
mtcars %>% assign_label(mpg)