r - 将具有两个字符串的行保留在同一行中

标签 r

在这样的数据框中:

df <- data.frame(id = c(1,2,3), text = c("hi my name is E","hi what's your name","name here"))

我想保留一行中同时包含 hi 和 name 单词的行。消耗输出示例:
df <- data.frame(id = c(1,2,3), text = c("hi my name is E","hi what's your name"))

我试试这个,但它不能正常工作:
library(tidyverse)
df %>%
    filter(str_detect(text, 'name&hi'))

最佳答案

一个简单的答案和两个更复杂的答案,只有当您要检查的单词超过 2 个时才真正需要

library(tidyverse)

df %>% 
  filter(str_detect(text, 'hi') & str_detect(text, 'name'))

df %>% 
  filter(rowSums(outer(text, c('hi', 'name'), str_detect)) == 2)

df %>% 
  filter(reduce(c('hi', 'name'), ~ .x & str_detect(text, .y), .init = TRUE))

关于r - 将具有两个字符串的行保留在同一行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941939/

相关文章:

r - 使用 R 使两个 shapefile 相交

r - r中的人口金字塔密度图

r - 从 R 中的 bestglm 包中提取最佳模型的公式

R:在删除之前评估对象名称

r - 从作者单位中提取国家名称

r - 来自 rjags 的语法错误

r - drop_na( ) 不能作用于 POSIX-lt 对象

r - 是否可以选择 left_join 列表列?

css - 增量幻灯片不适用于两列布局

r - 如何将频谱图矩阵转换为WAV文件