Rajpal Kulhari
Rajpal Kulhari

Reputation: 153

How to filter on column names in R

I would like to make a subset of a data frame in R that is based on multiple column names.

Example:

colnames <- c("RecentAVsB","RecentAMinusB","Label","TeamA","TeamB","Venue")

From this I would like to extract features those has "AVsB" or "AMinusB" or "Label" only. And these AvsB and AMinusB are multiple times, so don't want to extract using name. I tried..

myvars <-  grep("AMinusB" | "AVsB" | "Label", names(df), ignore.case=T)

But it gives error like:

Error in "AMinusB" | "AVsB" : 
  operations are possible only for numeric, logical or complex types

What is the best way to select only those specific features.

Upvotes: 1

Views: 6654

Answers (1)

akrun
akrun

Reputation: 887028

The pattern argument in grep should be a single string i.e. enclosed by two double quotes ("") or single ('').

grep("AMinusB|AVsB|Label", names(df), ignore.case=T)

Upvotes: 2

Related Questions