使用字符类变量的 mutate 和 recode (dplyr) 后标签丢失

问题描述

标记我的数据框变量时,我不得不一次又一次地在互联网上搜索。对我而言,在使用 dplyr 的上下文中执行此操作时,这不是一个小问题。

使用 sjlabelled 包中的 set_label 函数,我学会了创建标签向量并将其传递给数据帧的变量。但随后发生了意想不到的事情。

出于演示目的,我修改了 iris 数据集(将 Species 的类更改为 character)。 我想知道为什么变量 Species 的标签在 Species 作为字符类(case1)的情况下消失,而在 Species 作为因子类(case 2,在代码中注释掉)的情况下仍然存在 - 在使用 mutate 和 recode 之后。

情况 1(物种=字符类):

enter image description here

案例2(物种=因子类):

enter image description here

library(dplyr)
library(sjlabelled) # set_label function
# vector for variable names
label_names <- c("Length of sepal","Width of Sepal","Length of Petal","Width of Petal","A lot of Species")

# case 1
# change Species class to character for demonstrating
iris$Species <- as.character(iris$Species)

# case 2
# iris$Species <- as.factor(iris$Species)

iris_new <- iris %>% 
    set_label(label = label_names) %>% 
    mutate(Species = dplyr::recode(Species,"setosa" = "setosa_new","versicolor" = "versicolorandvirginica","virginica" = "versicolorandvirginica")) 

另外:

我如何使用这个简单的代码 label(iris$Species) <- "A lot of Species"dplyr 工作流程中,只需一个变量一个标签。 谢谢!

解决方法

我认为您发现了一个错误,或者更确切地说是缺乏兼容性。 dplyr::recode 似乎删除了 label 属性。

iris %>% 
    set_label(label = label_names) %>%
    pull(Species) %>% attributes()
#$label
#           Species 
#"A lot of Species"

iris %>% 
  set_label(label = label_names) %>% 
  mutate(Species = dplyr::recode(Species,"setosa" = "setosa_new","versicolor" = "versicolorandvirginica","virginica" = "versicolorandvirginica")) %>%
  pull(Species) %>% attributes()
#NULL

如果我们查看 dplyr::recodesource,我们会发现这是因为对于字符向量,调用了 as.character,它删除了属性。同时factor方法没有这样的调用。

但是为了回答您的最后一个问题,有一个 set_label 版本旨在重新标记数据框的一个或多个列,var_labels

library(dplyr)
library(sjlabelled)
iris %>% 
  set_label(label = label_names) %>% 
  mutate(Species = dplyr::recode(Species,"virginica" = "versicolorandvirginica")) %>%
  var_labels(Species = "A lot of Species") %>%
  View()

enter image description here