r - 检测数据框中的字符串模式并有条件地在 R 中填充另一个

标签 r loops for-loop stringr

我有一个包含文本和数字引用的数据框,以及一个可能出现在文本中的单词向量。我想要的是检查 words_df 中的单词出现在 text_df$text 中的每个实例,并记录来自 word_df 的单词和来自新数据帧 (edge_df) 中 text_df$ref 的数字引用。

text_df <- data.frame(text = c("John went to the shops", "Sarita hates apples", "Wendy doesn't care about this"),
                      ref = c("13.5", "1.9.9", "20.1"))

words_df <- data.frame(word = c("shops", "John", "apples", "Wendy", "this"))

edge_df <- data.frame(ref = NA, word = NA)

输出应该是这样的:

> edge_df
    ref   word
1  13.5  shops
2  13.5   John
3 1.9.9 apples
4  20.1  Wendy
5  20.1   this

它不是很优雅,但我认为 for 循环会起作用,其中使用 stringr::str_detect 根据文本检查每个单词,如果结果为 TRUE 它将记录单词和 ref:

for (i in 1:nrow(text_df)) {
  for (j in 1:nrow(words_df)) {
    if (str_detect(text_df$text[i], words_df$word[j]) == TRUE) {
      edge_df$ref <- text_df$ref[i]
      edge_df$word <- words_df$word[j]
    }
  }
}

这没有用,而且这个循环也没有几个变体。如果可能的话,我宁愿根本不使用循环,因为我正在使用的数据帧每个都有大约 1000 行,并且循环遍历它们需要太长时间。非常感谢对循环的任何修复,如果你可以在没有循环的情况下完成它,将获得奖励积分/ Prop 。

谢谢!

最佳答案

这是一个带有 str_extractunnest 的选项。我们将“文本”列中的单词提取到 list 中,并使用 unnest 扩展行

library(dplyr)
library(stringr)
library(tidyr)
text_df %>%
   transmute(ref, word = str_extract_all(text, 
                 str_c(words_df$word, collapse="|"))) %>%
   unnest(c(word))
# A tibble: 5 x 2
#  ref   word  
#  <chr> <chr> 
#1 13.5  John  
#2 13.5  shops 
#3 1.9.9 apples
#4 20.1  Wendy 
#5 20.1  this  

关于r - 检测数据框中的字符串模式并有条件地在 R 中填充另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63885651/

相关文章:

根据顺序删除重复项

jsf - 迭代 primefaces 数据表中的 List<Map<String, String>> ?

python - 将列表附加到另一个列表时遇到问题

python-3.x - 对于每一行 "for loop"无法在我的脚本中实现

mysql - 批处理文件摆脱了输出中的迭代器编号

r - 基于正则表达式模式连接列表的元素

r - R中每小时间隔的聚合时间列

r - 列表中列的数据类型 - R

c# - 字典中按键识别速度

swift - 为 for in 循环添加 break 或 continue 语句