在 mutate 中添加变量标签

jam*_*121 4 r dplyr tidyverse

我正在重新编写一些旧代码以方便学习tidyverse. 在上面的代码我会做,从目前的变量derrived新的变量,我想给这些新的变量,使用标签属性labelHmisc包。这看起来像这样。

library(Hmisc)

iris$new <- ifelse(iris$Species == 'setosa', 1, 0)
label(iris$new) <- "New Variable"
Run Code Online (Sandbox Code Playgroud)

这给出了这个结果

> str(iris$new)
 'labelled' num [1:150] 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "label")= chr "New Variable"
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我想知道是否有办法在 mutate 调用中应用这种相同类型的东西。

Dic*_*oyT 7

我们可以使用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"
Run Code Online (Sandbox Code Playgroud)