Is it possible to select columns based on variable labels?

Viewed 321

With a very wide dataset, is it possible to use variable labels to select columns?

library(expss)
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)
mtcars %>% 
  select(contains("Miles"))

This doesn't work because it looks in the column names. Can it look at labels instead?

Edit: I should add, aside from the obvious of converting the labels to column names.

1 Answers

We could get the attributes 'label', check for the 'Miles'

library(dplyr)
library(stringr)
mtcars %>% 
   select(where(~ str_detect(attributes(.)$label, 'Miles')))

-output

#                      mpg
#Mazda RX4           21.0
#Mazda RX4 Wag       21.0
#Datsun 710          22.8
#Hornet 4 Drive      21.4
#Hornet Sportabout   18.7
#Valiant             18.1
#Duster 360          14.3
#Merc 240D           24.4
#Merc 230            22.8
#Merc 280            19.2
#Merc 280C           17.8
#Merc 450SE          16.4
# ..

Or using base R (with R 4.1.0), loop over the columns with lapply, extract the labels attribute, use grep to return the elements that matches the pattern 'Miles', get the names and use that in select of subset

mtcars |>  
    lapply(\(x) attributes(x)$label) |> 
    grep(pattern = 'Miles', value = TRUE) |> 
    names() |>
    {\(x) subset(mtcars, select = x)}()

-output

#                      mpg
#Mazda RX4           21.0
#Mazda RX4 Wag       21.0
#Datsun 710          22.8
#Hornet 4 Drive      21.4
#Hornet Sportabout   18.7
#Valiant             18.1
#Duster 360          14.3
#Merc 240D           24.4
#Merc 230            22.8
#Merc 280            19.2
# ...
Related