【发布时间】:2013-05-09 19:00:43
【问题描述】:
我有一个项目列表和一个搜索词列表,我正在尝试做两件事:
- 在项目中搜索与任何搜索词匹配的项,并返回 true 如果找到匹配项。
- 对于所有返回 true 的项目(即存在匹配项),我想 还返回在步骤 1 中匹配的原始搜索词。
所以,给定以下数据框:
items
1 alex
2 alex is a person
3 this is a test
4 false
5 this is cathy
以及以下搜索词列表:
"alex" "bob" "cathy" "derrick" "erica" "ferdinand"
我想创建以下输出:
items matches original
1 alex TRUE alex
2 alex is a person TRUE alex
3 this is a test FALSE <NA>
4 false FALSE <NA>
5 this is cathy TRUE cathy
第 1 步相当简单,但第 (2) 步有问题。要创建“匹配”列,我使用grepl() 创建一个变量,如果d$items 中的一行在搜索词列表中,则该变量为TRUE,否则为FALSE。
对于第 2 步,我的想法是我应该能够在指定 value = T 时只使用 grep(),如下面的代码所示。但是,这会返回错误的值:它不会返回 grep 匹配的原始搜索词,而是返回匹配项的值。所以我得到以下输出:
items matches original
1 alex TRUE alex
2 alex is a person TRUE alex is a person
3 this is a test FALSE <NA>
4 false FALSE <NA>
5 this is cathy TRUE this is cathy
这是我现在使用的代码。任何想法将不胜感激!
# Dummy data and search terms
d = data.frame(items = c("alex", "alex is a person", "this is a test", "false", "this is cathy"))
searchTerms = c("alex", "bob", "cathy", "derrick", "erica", "ferdinand")
# Return true iff search term is found in items column, not between letters
d$matches = grepl(paste("(^| |[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVQXYZ])",
searchTerms, "($| |[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVQXYZ])", sep = "",
collapse = "|"), d[,1], ignore.case = TRUE
)
# Subset data
dMatched = d[d$matches==T,]
# This is where the problem is: return the value that was originally matched with grepl above
dMatched$original = grep(paste("(^| |[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVQXYZ])",
searchTerms, "($| |[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVQXYZ])", sep = "",
collapse = "|"), dMatched[,1], ignore.case = TRUE, value = TRUE
)
d$original[d$matches==T] = dMatched$original
【问题讨论】:
-
你可以用
[:alpha:]替换长字符串。 -
您可能想查看
regmatches函数。 -
@Thomas:感谢您的提示。但是,[:alpha:] 和其他预定义的字符类似乎对我不起作用。它必须与我的语言环境有关。从关于字符类的正则表达式文档中:“(因为它们的解释取决于语言环境和实现,所以最好避免使用它们。)指定所有 ASCII 字母的唯一可移植方法是将它们全部列为字符类 [ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]。 "
-
@SteveS 是的,通常对我有用,所以我不知道该警告总体上有多准确。
-
语法为
grep("[[:alpha:]]", c("123", "one"))或为否定"[^[:alpha:]]";如果文件的编码很重要,那么您可能不会对寻找 ASCII 字母感到满意,因此“便携式”注释可能与您解释它的方式无关。