how do I grep in R?

冷暖自知 提交于 2019-12-02 20:18:28

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

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!