使用通配符进行模式匹配 [英] Pattern matching using a wildcard

查看:92
本文介绍了使用通配符进行模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用通配符识别字符串?

How do I identify a string using a wildcard?

我找到了 glob2rx,但我不太明白如何使用它.我尝试使用以下代码选择以单词 blue 开头的数据框行:

I've found glob2rx, but I don't quite understand how to use it. I tried using the following code to pick the rows of the data frame that begin with the word blue:

# make data frame
a <- data.frame( x =  c('red','blue1','blue2', 'red2'))

# 1
result <- subset(a, x == glob2rx("blue*") )

# 2
test = ls(pattern = glob2rx("blue*"))
result2 <- subset(a, x == test )

# 3
result3 <- subset(a, x == pattern("blue*") )

然而,这些都没有奏效.我不确定是否应该使用不同的函数来尝试执行此操作.

However, neither of these worked. I'm not sure if I should be using a different function to try and do this.

推荐答案

如果你想检查数据框内的元素,你不应该使用 ls() 它只查看对象的名称当前工作区(或者如果在当前环境中的函数内使用).此类对象中的行名或元素对 ls() 不可见(当然,除非您向 ls(.) 调用添加环境参数).尝试使用 grep() 这是字符向量模式匹配的主力函数:

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

如果你想使用子集,那么考虑密切相关的函数 grepl() ,它返回一个可以在子集参数中使用的逻辑向量:

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

在子集()中添加一个正确"使用 glob2rx:

Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

在我回到这个问题之前,我认为我并没有真正理解 glob2rx.(我确实理解作为提问者困难根源的范围界定问题.任何阅读本文的人现在都应该向下滚动到 Gavin 的答案并投票.)

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)

这篇关于使用通配符进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆