【问题标题】:R: grep unintendedly outputs more than a single string matchR:grep 意外输出多个字符串匹配
【发布时间】:2019-05-15 13:20:35
【问题描述】:

我有一个包含 1 个变量和 5,000 行的数据框,其中每个元素都是一个字符串。

1. "Am open about my feelings."                   
2. "Work hard"                                 
3. "Work harder than others."
   .....
5000. "Speak softly."           

我需要找到并输出与多个元素相对应的行索引,即每个完全匹配的元素一个行索引。目前,我使用以下功能:

z <- lapply(df, function(p) {
     grep(pattern = p, test[ , 1])})

它运行良好,并为我正在寻找的每个元素输出行索引。但是我注意到它变得贪婪,因此代码不仅可以找到确切的字符串,还可以找到恰好包含原始字符串的较大字符串。例如,如果代码正在搜索元素“Work hard.”的行索引,它将输出 2 个行索引。一个用于完全匹配,另一个用于包含原始字符串的较大字符串,“Work hard than others”。

[1] 2 3

到目前为止,我只解决了部分问题:

我在网站上搜索了大量与 grep 相关的线程,并找到了一个有效的解决方案,但只能一次找到一个字符串短语的完全匹配。

grep("\\bWork hard*\\b", df$value)

由于这不是一个有效的解决方案,我想寻求帮助以调整 lapply 代码以使其仅找到确切的刺痛。我还尝试在 lapply 代码的各个部分添加“\\b”和“*\\b”,但没有成功。

编辑。添加了可重现的示例

test_1 是包含近 5000 个字符串元素的数据框,但对于
一个可重现的小例子,我只会提供 5 个字符串元素

test_1 <- c( 
         "Like to watch children open presents.",         
          "Work hard.",                              
          "Work harder after a failure.",                   
          "Am open about my feelings.",                
          "Show my sadness.")

library(dplyr)

test_1 <- tbl_df(test_1) # tablulate as datafarme 

df 是一个具有 3 个字符串值的字符对象:

df <- c("Work hard.", 
        "Show my sadness.", 
        "Like to watch children open presents.")

下面是获取 df 的每个元素的函数,在 test_1 中找到它的匹配项 并从 test_1 输出相应的行索引

j <- lapply(df, function(p) {
grep(pattern = p, test_1[ , 1])})
j

# Output
[[1]]
[1] 2 3 # as you see it finds two matches. One is the exact match: "Work hard." row index 2. Another one is a larger string that contains wording of the original string: row index 3. But I only want an exact match, i.e. index 2

[[2]]
[1] 5

[[3]]
[1] 1

我想要的:每个完全匹配的元素都有一个单行索引

[[1]]
[1] 2 

[[2]]
[1] 5

[[3]]
[1] 1

【问题讨论】:

  • 你能展示一个可重复的小例子吗?什么是test
  • 您可以在向量中的每个单词上粘贴单词边界p
  • 谢谢,我会尽快发布一个可重现的示例
  • 如果这是一个向量,你为什么使用lapply
  • @akrun 我根据要求添加了一个可重现的示例。提前感谢您的帮助

标签: r regex string match lapply


【解决方案1】:

因此,使用 lapplygrep 您可以使用以下代码:

lapply(df, function(z) grep(paste0("^",z,"$"), test_1))

结果是

[[1]]
[1] 2

[[2]]
[1] 5

[[3]]
[1] 1

这通过使用锚点来工作。 ^ 是字符串开头的锚点,$ 是字符串结尾的锚点。使用paste0 将锚点与df 中感兴趣的字符串组合起来,以创建以下内容:

[1] "^Work hard.$"                            "^Show my sadness.$"                      "^Like to watch children open presents.$"

并通过将搜索字段限制为介于 ^$ 之间的任何内容来搜索 EXACT 整个字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多