0

I have a dataframe dat that has many variables like

"x_tp1_y"
"g_tp1_z"
"f_tp2_h"

I would like to extract elements that include "tp1".

I already tried this:

grep("tp1", dat)

grepl("tp1", dat)

dat["tp1",]

I just want R to give me elements with this pattern so I do not have to type in all variable names that are in the dataframe dat.
Like this:

command that extracts elements with pattern "tp1" R returns parts of the dataframe that have pattern "tp1":

x_tp1_y   g_tp1_z
      1         2
      0         3

And then I would like to create a new dataframe.

I know that I just can use

newdat <- data.frame( dat[[1]], dat[ c(1:30)]) 

but I have so many elements in my dataframe that this would take ages.

Thank you for your help!

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
a.henrietty
  • 55
  • 1
  • 1
  • 8

1 Answers1

2
dat[,grep("tp1", colnames(dat))]

grep finds the index numbers in the column names of the data.frame (the vector colnames(dat)) that contain the necessary pattern. "[" subsets

Grada Gukovic
  • 1,228
  • 7
  • 13
  • You should give an explanation of what the code does. These *code-only answers* are many times flagged for deletion. (I have upvoted because it seems to answer the question but do edit the answer with a few words.) – Rui Barradas Jul 13 '19 at 10:58