Skip to content
Prev 393610 / 398503 Next

Removing variables from data frame with a wile card

You'll want to use grep() or grepl(). By default, grep() uses extended
regular expressions to find matches, but you can also use perl regular
expressions and globbing (after converting to a regular expression).
For example:

grepl("^yr", colnames(mydata))

will tell you which 'colnames' start with "yr". If you'd rather you
use globbing:

grepl(glob2rx("yr*"), colnames(mydata))

Then you might write something like this to remove the columns starting with yr:

mydata <- mydata[, !grepl("^yr", colnames(mydata)), drop = FALSE]
On Sat, Jan 14, 2023 at 1:56 AM Steven T. Yen <styen at ntu.edu.tw> wrote: