Losing variable label after certain changes to variable inside mutate

161 Views Asked by At

This is similar to the question "Losing all variable labels when mutating a column" from a few months ago. Depending on what type of change you do inside of a mutate to the variable in question, you'll either lose or not lose the variable's label.

Here's an example:

library(tidyverse)
library(labelled)

mtcars <- mtcars %>% 
  as_tibble() %>% 
  set_variable_labels(
    qsec = "Q Sec Label"
  )

mtcars %>% var_label()

mtcars %>% 
  mutate(qsec = log(qsec)) %>% 
  var_label()

mtcars %>% 
  mutate(qsec = cumsum(qsec)) %>% 
  var_label()

As the output should show you if you run this code, the label doesn't disappear after you do a log transformation. But for some strange reason, if you do a cumsum mutate the label mysteriously disappears. It also disappears if you do a case_when mutate. This is really unexpected and inexplicable behavior. I'm not sure how to figure out why it does this.

If anyone can figure out how to make it NOT drop the variable label no matter what is done inside a mutate function to the variable, I would be extremely grateful! Thanks!

0

There are 0 best solutions below