1

我在 SPSS 中有一个数据集,我正在使用“haven”库将其读入 R

df <- structure(list(SC155Q09HA = structure(c(2, 1, 1, 2, 1, 2, 3, 
      4, 3, 1), label = "School's capacity using digital devices: An effective online learning support platform is available", labels = c(`Strongly disagree` = 1, 
      Disagree = 2, Agree = 3, `Strongly agree` = 4, `Valid Skip` = 5, 
      `Not Applicable` = 7, Invalid = 8, `No Response` = 9), class = "haven_labelled")), row.names = c(NA, 
      -10L), class = c("tbl_df", "tbl", "data.frame"))

我正在尝试从数据框中提取标签,并且可以在基础 R 中执行此操作:

library(tidyverse)
library(magrittr)
library(haven)

focus <- quo(SC156Q05HA)

 attr(df$SC155Q09HA,"label")

>[1] "School's capacity using digital devices: An effective online learning support platform is available"

但不是以带有选择变量的 dplyr 样式方式:

df[quo_name(focus)] %>% attr("label")

>NULL

df %>% select(!!focus) %>% attr("label")

>NULL

我知道这两个不起作用的示例返回小标题,而第一个返回标记为双精度。我如何使它们等效?

4

1 回答 1

1

你可以做:

focus <- quo(SC155Q09HA) # Changed to match the data provided

df %>% pull(!!focus) %>% attr("label")

[1] "School's capacity using digital devices: An effective online learning support platform is available"

您使用的尝试select()将 tibble 传递给attr()没有标签属性,因此它返回NULL.

如果您有多个标签要提取使用purrr::map_chr()

df %>% purrr::map_chr(attr, "label")
于 2019-12-12T12:44:34.770 回答