rhmiscr-labelled

How to identify Hmisc labelled vectors


I want to use map() from purrr to identify which variables in a dataset are labelled.

Unfortunately these labelled vectors were created in the Hmisc package and don't register as TRUE when you run them through the is.labelled() function (from the labelled package).

age <- c(21,65,43)
y   <- 1:3
label(age) <- "Age in Years"

library(labelled)
score <- labelled(sample(5, 3, replace = TRUE), c(Bad = 1, Good = 5))
score

weight <- c(71.5, 87.3, 100.4)

d <- data.frame(age, score, weight)

d %>%
  map(is.labelled)

# $age
# [1] FALSE
# 
# $score
# [1] TRUE
# 
# $weight
# [1] FALSE

Does anyone know how to identify variables created in the Hmisc package?


Solution

  • d %>% map(~ is.labelled(.x) | (label(.x) != ""))
    
    #> $age
    #> [1] TRUE
    #> 
    #> $score
    #> [1] TRUE
    #> 
    #> $weight
    #> [1] FALSE
    

    If we run Hmisc::label() on an unlabelled vector, it return an empty string. So, label(.x) != "", checks if the label is present or not. In combination with labelled::is.labelled(), we can identify everything that is labelled whether through {Hmisc} or {labelled} package.

    unlabelled_Hmisc <- c(42, Inf)
    labelled_Hmisc <- c(1.618, 3.14); label(labelled_Hmisc) <- "Phi and Pi"
    
    label(unlabelled_Hmisc) ## returns an empty string
    #> [1] ""
    label(labelled_Hmisc)
    #> [1] "Phi and Pi"
    

    Created on 2025-06-14 with reprex v2.1.1