gpt4 book ai didi

r - 在 mutate 中添加变量标签

转载 作者:行者123 更新时间:2023-12-03 20:29:10 25 4
gpt4 key购买 nike

我正在重新编写一些旧代码以方便学习tidyverse .在前面的代码中,我将从当前变量派生出新变量,并使用 label 为这些新变量赋予标签属性。来自 Hmisc包裹。这看起来像这样。

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"

enter image description here

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

最佳答案

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

关于r - 在 mutate 中添加变量标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53751682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com