Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add variable labels within mutate

Tags:

r

dplyr

tidyverse

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"

enter image description here

I was wondering if there is a way to apply this same type of thing within a mutate call.

like image 618
jamesguy0121 Avatar asked Mar 05 '23 21:03

jamesguy0121


1 Answers

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"
like image 70
dave-edison Avatar answered Mar 16 '23 04:03

dave-edison