str_detect R的多个字符串

Mag*_*k.M 14 string r django-errors

我想找到多个字符串并将其放在变量中,但是我不断收到错误.

queries <- httpdf %>% filter(str_detect(payload, "create" || "drop" || "select"))
Error: invalid 'x' type in 'x || y'

queries <- httpdf %>% filter(str_detect(payload, "create" | "drop" | "select"))
Error: operations are possible only for numeric, logical or complex types

queries1 <- httpdf %>% filter(str_detect(payload, "create", "drop", "select"))
Error: unused arguments ("drop", "select")
Run Code Online (Sandbox Code Playgroud)

这些都没有奏效.还有其他方法可以做到str_detect或者我应该尝试别的吗?我希望它们也出现在同一列中.

小智 28

在我看来,一个更简单的方法,你想要找到的很短的字符串列表可以是:

queries <- httpdf %>% filter(str_detect(payload, "create|drop|select"))
Run Code Online (Sandbox Code Playgroud)

因为这实际上是什么

[...] paste(c("create", "drop", "select"),collapse = '|'))[...]

是的,正如@penguin之前所建议的那样.

对于要检测的较长字符串列表,我首先将单个字符串存储到向量中,然后使用@ penguin的方法,例如:

strings <- c("string1", "string2", "string3", "string4", "string5", "string6")
queries <- httpdf %>% 
  filter(str_detect(payload, paste(strings, collapse = "|")))
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,strings如果您愿意或必须使用,您也可以在以后轻松使用该向量.


pen*_*uin 26

这是解决此问题的一种方法:

queries1 <- httpdf %>% 
  filter(str_detect(payload, paste(c("create", "drop", "select"),collapse = '|')))
Run Code Online (Sandbox Code Playgroud)