【问题标题】:Add variable labels within mutate在 mutate 中添加变量标签
【发布时间】:2018-12-12 21:32:45
【问题描述】:

我正在修改一些旧代码以方便学习tidyverse。在前面的代码中,我将创建从现有变量派生的新变量,并使用 Hmisc 包中的 label 为这些新变量赋予标签属性。这看起来像这样。

library(Hmisc)

iris$new <- ifelse(iris$Species == 'setosa', 1, 0)
label(iris$new) <- "New Variable"

给出这个结果

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

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

【问题讨论】:

  • 这是您要找的吗? result &lt;- iris %&gt;% mutate(New.Variable = ifelse(Species == 'setosa', 1, 0))
  • 不,我知道如何使用 mutate 创建变量。在 mutate 中创建变量后,我试图弄清楚如何操作变量属性 label

标签: r dplyr tidyverse


【解决方案1】:

我们可以使用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"

【讨论】:

  • 是的,这正是我想要的,它可以像这样在一个 mutate 调用中链接在一起,iris &lt;- iris %&gt;% mutate(new = ifelse(iris$Species == 'setosa', 1, 0) %&gt;% structure(label = "New Variable")) 这正是我想要的。谢谢。
【解决方案2】:

有点丑,你也可以这样做

iris %>% 
mutate(new =`label<-`(ifelse(Species == 'setosa', 1, 0), value="New Variable")) 

这不会绕过label&lt;- 默认情况下结构会跳过的任何检查。您也可以将其包装在一个函数中以使其更简洁。

labelled <- function(x, label) {
  label(x) <- label
  x
}
iris %>% 
  mutate(new =labelled(ifelse(Species == 'setosa', 1, 0), "New Variable"))
# or
iris %>% 
  mutate(new =ifelse(Species == 'setosa', 1, 0) %>% labelled("New Variable")) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多