1

I have the following tibble:

library(tidyverse)
set.seed(1)
df <- data_frame(gene=LETTERS[seq( from = 1, to = 10 )], x1.control=runif(10),x2.control=runif(10),y1.control=runif(10),y2.control=runif(10))

Which looks like this:

> df
# A tibble: 10 × 5
    gene x1.control x2.control y1.control y2.control
   <chr>      <dbl>      <dbl>      <dbl>      <dbl>
1      A 0.26550866  0.2059746 0.93470523  0.4820801
2      B 0.37212390  0.1765568 0.21214252  0.5995658
3      C 0.57285336  0.6870228 0.65167377  0.4935413
4      D 0.90820779  0.3841037 0.12555510  0.1862176
5      E 0.20168193  0.7698414 0.26722067  0.8273733
6      F 0.89838968  0.4976992 0.38611409  0.6684667
7      G 0.94467527  0.7176185 0.01339033  0.7942399
8      H 0.66079779  0.9919061 0.38238796  0.1079436
9      I 0.62911404  0.3800352 0.86969085  0.7237109
10     J 0.06178627  0.7774452 0.34034900  0.4112744

Given a string e.g

wanted_col_pat = 'control'

I would like to obtain the columns that contain that string:

# A tibble: 10 × 2
   x1.control x2.control
        <dbl>      <dbl>
1  0.26550866  0.2059746
2  0.37212390  0.1765568
3  0.57285336  0.6870228
4  0.90820779  0.3841037
5  0.20168193  0.7698414
6  0.89838968  0.4976992
7  0.94467527  0.7176185
8  0.66079779  0.9919061
9  0.62911404  0.3800352
10 0.06178627  0.7774452

How can I do that with grep and tidyverse?

neversaint
  • 60,904
  • 137
  • 310
  • 477

1 Answers1

7

You can use dplyr::select_if and grepl. For example, to match all columns where column name contains "control":

library(dplyr)
df %>%
  select_if(grepl("control", names(.)))
neilfws
  • 32,751
  • 5
  • 50
  • 63