gpt4 book ai didi

R 过滤包含单词组合的行

转载 作者:行者123 更新时间:2023-12-04 11:31:05 26 4
gpt4 key购买 nike

我正在处理文本数据,并正在寻找过滤问题的解决方案。

我设法找到了一个解决方案,可以过滤包含“Word 1”的行 '字 2'

这是可重现的代码

df=data.frame(UID=c(1,2,3,4,5),Text=c("the quick brown fox jumped over the lazy dog",
"long live the king",
"I love my dog a lot",
"Tomorrow will be a rainy day",
"Tomorrow will be a sunny day"))


#Filter for rows that contain "brown" OR "dog"
filtered_results_1=dplyr::filter(df, grepl('brown|dog', Text))

但是,当我过滤同时包含“Word 1”的行时 'Word 2',它不起作用。
#Filter for rows that contain "brown" AND "dog"
filtered_results_2=dplyr::filter(df, grepl('brown & dog', Text))

无法找出正确的语法,任何帮助将不胜感激。

最佳答案

您可以使用 stringr::str_count :

dplyr::mutate(df, test = stringr::str_count(Text,'brown|dog'))
# UID Text test
# 1 1 the quick brown fox jumped over the lazy dog 2
# 2 2 long live the king 0
# 3 3 I love my dog a lot 1
# 4 4 Tomorrow will be a rainy day 0
# 5 5 Tomorrow will be a sunny day 0

dplyr::filter(df, stringr::str_count(Text,'brown|dog') == 2)
# UID Text
# 1 1 the quick brown fox jumped over the lazy dog

它会计数 dogbrown尽管它们发生了多少次

以下是更一般的,不如一些优雅,但您可以方便地将搜索到的词放在一个向量中:
dplyr::filter(df, purrr::map_int(strsplit(as.character(Text),'[[:punct:] ]'),
~sum(unique(.) %in% c("brown","dog"))) == 2)

# UID Text
# 1 1 the quick brown fox jumped over the lazy dog

关于R 过滤包含单词组合的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52117894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com