Skip to contents

It may sometimes happen that transformations you apply to a dataframe do not retain variable labels. In such a case it might be useful to have the initial dataframe stored in a separate variable to be able to copy labels from it. This function does exactly that: it copies variable labels from one dataframe to another overwriting values if any were present. Copying is done based on matching variable names.

Usage

srv_labels_copy(data_to, data_from)

Arguments

data_to

dataframe to copy labels to

data_from

dataframe to copy labels from

Value

a data.frame with copied labels

Examples


library(dplyr)
library(forcats)

data <- 
  mtcars %>% 
  as_tibble() %>% 
  select(mpg, cyl) %>% 
  mutate(car = rownames(mtcars))

attr(data$cyl, "label") <- "Number of Cylinders"

# convert cyl to factor
data2 <- 
  data %>% 
  mutate(across(cyl, factor))

# label is dropped  
attr(data2$cyl, "label")
#> NULL

# copy label from the original dataframe
data3 <- 
  data2 %>% 
  srv_labels_copy(data)

attr(data3$cyl, "label")
#> [1] "Number of Cylinders"