简体   繁体   中英

R haven: accessing column label from imported SPSS file

I have a dataset in SPSS that I am reading into R using the 'haven' library

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"))

I'm trying to extract the label from the dataframe and can do this in base 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"

But not in in a dplyr style way with a variable for selection:

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

>NULL

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

>NULL

I understand that the two none-working examples return tibbles, whilst the first returns a labelled double. How do I make them equivalent?

You can do:

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"

Your attempt using select() passes the tibble to attr() which doesn't have a label attribute, hence it returns NULL .

If you have multiple labels to extract use purrr::map_chr()

df %>% purrr::map_chr(attr, "label")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM