Subset data to contain only label of columns whose names match a condition

Viewed 41

I have the following sample data frame:

M <- c(1, 2)
S <- c(3, 4)
old_df <- data.frame(M, S)
label(old_df$M) <- "My Mathematics Variable"
label(old_df$S) <- "My Science Variable"

And I want to filter in order to only have columns that contains "Math" in the label of the columns.

Thanks!

1 Answers

You can use grepl:

old_df[, grepl("Math", label(old_df))]
# My Mathematics Variable 
# [1] 1 2

data

library(Hmisc)
old_df <- structure(list(M = structure(c(1, 2), label = "My Mathematics Variable", class = c("labelled", 
"numeric")), S = structure(c(3, 4), label = "My Science Variable", class = c("labelled", 
"numeric"))), row.names = c(NA, -2L), class = "data.frame")
Related