3

My data frame has over 120 columns (variables) and I would like to create subsets bases on column names.

For example I would like to create a subset where the column name includes the string "mood". Is this possible?

KillianDS
  • 16,936
  • 4
  • 61
  • 70
Max
  • 31
  • 1
  • 2
  • 2
    Probably something like `df[grepl("mood", names(df))]` if your data called `df` – David Arenburg Mar 03 '15 at 08:56
  • `df[grepl("mood", names(df), fixed = TRUE)]` does not use regular expressions, i.e. in "mood." the dot is not for an arbitrary char - probably that what the op wants? Additionally it is faster (which will not really matter here) – Patrick Roocks Mar 03 '15 at 09:23

1 Answers1

2

I generally use

    SubData <- myData[,grep("whatIWant", colnames(myData))]

I know very well that the "," is not necessary and colnames could be replaced by names but it would not work with matrices and I hate to change the formalism when changing objects.

cmbarbu
  • 4,354
  • 25
  • 45