0

Below is my example data:

set.seed(13435)
x <- data.frame("Alex"=sample(1:5),"1Alx1"=sample(6:10),"Peter"=sample(11:15))

and it will return the an example table:

  Alex X1Alx1 Peter
1    2       8    15
2    3       7    12
3    5       6    14
4    1      10    11
5    4       9    13

I want to extract new table by selecting specific keyword from the header. For example, I want to only extract my new table with keyword "Al" from the header and the new table should be like below:

  Alex X1Alx1 
1    2       8   
2    3       7    
3    5       6   
4    1      10   
5    4       9   

I know there is method by using %in% to select one variable but how do I extract all the data by using keywords from header?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Alex
  • 1,097
  • 2
  • 9
  • 12

1 Answers1

1

We can use grep from base R

x[grep("Al", names(x))]
#      Alex X1Alx1
#1    2      8
#2    3      7
#3    5      6
#4    1     10
#5    4      9
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, it works. One more question, what should I do if I multiple condition? – Alex Sep 11 '16 at 18:32
  • @Alex it depends on your condition. suppose you have `Al` and `Bl` then `x[grep("Al|Bl", names(x))]` – akrun Sep 12 '16 at 01:21