Reputation: 4346
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?
Upvotes: 2
Views: 679
Reputation: 34406
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")
Upvotes: 3