小编Mal*_*hot的帖子

R中检查一个字符串是否出现在另一个字符串中

我有一个包含这样的句子的小标题:

df <- tibble(sentences = c("Bob is looking for something", "Adriana has an umbrella", "Michael is looking at..."))
Run Code Online (Sandbox Code Playgroud)

另一个包含一长串名字:

names <- tibble(names = c("Bob", "Mary", "Michael", "John", "Etc."))
Run Code Online (Sandbox Code Playgroud)

我想查看句子是否包含列表中的名称,并添加一列来指示是否是这种情况,并获取以下 tibble :

wanted_df <- tibble(sentences = c("Bob is looking for something", "Adriana has an umbrella", "Michael is looking at..."), check = c(TRUE, FALSE, TRUE))
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过,但没有成功:

df <- df %>%
mutate(check = grepl(pattern = names$names, x = df$sentences, fixed = TRUE))
Run Code Online (Sandbox Code Playgroud)

并且 :

check <- str_detect(names$names %in% df$sentences)
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助;)

regex string compare r

4
推荐指数
2
解决办法
82
查看次数

标签 统计

compare ×1

r ×1

regex ×1

string ×1