I am in the process of reworking some old code in order to facilitate learning the tidyverse. In the previous code I would make new variables derrived from present variables, and I would give these new variables a label attribute using label from the Hmisc package. This would look like this.
library(Hmisc)
iris$new <- ifelse(iris$Species == 'setosa', 1, 0)
label(iris$new) <- "New Variable"
which gives this result
> str(iris$new)
 'labelled' num [1:150] 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "label")= chr "New Variable"

I was wondering if there is a way to apply this same type of thing within a mutate call.
We can use structure():
library(Hmisc)
library(dplyr)
iris <- iris %>% 
  mutate(new = structure(ifelse(iris$Species == 'setosa', 1, 0), label = "New Variable"))
label(iris$new)
#[1] "New Variable"
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With