how do I grep in R?

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

> grep("foo",names(data), value=T)
[1] "foo-"     "foo1234-" "123foo-" 

if value is true, it returns the content instead of the index


Use subset in combination with regular expressions:

subset(your_data, regexpr("foo", your_data$your_column_to_match) > 0))

If you just care about a dataset with one column I guess you do not need to specify a column name...

Philip

Tags:

R

Subset