本文介绍了我如何在R中grep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据其名称的子集来选择行,例如

如果我有以下数据:


$ (c(91,92,108,104,87,91,91,97,81,98),
.Names)的数据结构(c(91,92,108,104,87,91,91,97,81,98),b $ b pre> = c(fee-,fi,fo-,fum-,foo-,foo1234-,123foo-,
fum-,fum- ,fum-))

如何选择匹配'foo'的行?



使用grep()不起作用:
$ b

  grep('foo' ,数据)

返回:



<$ p $ 或者,有没有更好的办法?



谢谢! 您需要grep数据的names属性,而不是values属性。



对于您的示例,请使用

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

另外一个干净的方法是使用数据框。

 >数据<  -  data.frame(值= c(91,92,108,104,87,91,91,97,81,98),
names = c(fee-,fi, foo-,fum-,foo-,foo1234-,123foo-,
fum-,fum-,fum-))

> data $ values [grep(foo,data $ names)]
[1] 87 91 91


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!

解决方案

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

这篇关于我如何在R中grep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:15