Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I grep in R?

Tags:

I would like to choose rows based on the subsets of their names, for example

If I have the following data:

data <- structure(c(91, 92, 108, 104, 87, 91, 91, 97, 81, 98),  .Names = c("fee-", "fi", "fo-", "fum-", "foo-", "foo1234-", "123foo-",  "fum-", "fum-", "fum-")) 

how do I select the rows matching 'foo'?

using grep() doesn't work:

 grep('foo', data) 

returns:

integer(0) 

what am I doing wrong? or, is there a better way?

Thanks!

like image 896
David LeBauer Avatar asked Nov 18 '10 23:11

David LeBauer


People also ask

Can I use grep in R?

grep() function in R Language is used to search for matches of a pattern within each element of the given string. Parameters: pattern: Specified pattern which is going to be matched with given elements of the string.

What does the grep () function do?

The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

What does grep stand for in R?

Introduction. grep is a utility for searching text for lines that match a regular expression. The name stands for: globally search for a regular expression and print matching lines.


1 Answers

You need to grep the names property of data, not the values property.

For your example, use

> grep("foo",names(data)) [1] 5 6 7 > data[grep("foo",names(data))]   foo- foo1234-  123foo-    87       91       91  

One other clean way to do this is using data frames.

> data <- data.frame(values=c(91, 92, 108, 104, 87, 91, 91, 97, 81, 98),                     names = c("fee-", "fi", "fo-", "fum-", "foo-", "foo1234-", "123foo-",                     "fum-", "fum-", "fum-"))  > data$values[grep("foo",data$names)] [1] 87 91 91 
like image 85
Alex Brown Avatar answered Oct 21 '22 17:10

Alex Brown