Home > Enterprise >  How to show only one type of attribute from a labelled dataframe in R
How to show only one type of attribute from a labelled dataframe in R

Time:08-20

I want to show only one type of attribute (e.g. labels), and this code shows all three types.

library(tidyverse)
library(labelled)

df <- tibble(age = c(10,20,30),
             sex = c(1,1,2))

df$sex <- labelled(
  c(1, 1, 2),
  c(Male = 1, Female = 2),
  label = "Assigned sex at birth"
)

# how to show only one attribute e.g. labels?
showAt <- function(db, v) {
  at <- df %>% 
    pull({{v}}) %>% 
    attributes
  return(at)
}

showAt(df, sex)
#> $labels
#>   Male Female 
#>      1      2 
#> 
#> $label
#> [1] "Assigned sex at birth"
#> 
#> $class
#> [1] "haven_labelled" "vctrs_vctr"     "double"
Created on 2022-08-19 by the reprex package (v2.0.1)

CodePudding user response:

We can use pluck

library(purrr)
library(dplyr)
showAt <- function(db, v) {
  at <- db %>% 
    pull({{v}}) %>% 
    attributes %>%
    pluck("labels")
  return(at)
}

-testing

> showAt(df, sex)
  Male Female 
     1      2 

CodePudding user response:

attributes(x) returns the object's complete attribute list, whereas attr(x, which) accesses a specific attribute.

showAt <- function(db, v) {
  at <- db %>% 
    pull({{v}}) %>% 
    attr("labels")
  return(at)
}

showAt(df, sex)

#  Male Female 
#     1      2
  •  Tags:  
  • r
  • Related