how do I grep in R?

大城市里の小女人 提交于 2019-12-03 05:40:53

问题


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!


回答1:


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



回答2:


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




回答3:


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

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



来源:https://stackoverflow.com/questions/4220631/how-do-i-grep-in-r

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