str_detect R的多个字符串

时间:2016-03-12 19:39:57

标签: r string 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")

这些都没有奏效。是否有另一种方法可以使用str_detect或者我应该尝试其他方法吗?我希望它们也显示在同一列中。

2 个答案:

答案 0 :(得分:19)

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

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

答案 1 :(得分:15)

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

queries <- httpdf %>% filter(str_detect(payload, "create|drop|select"))

因为这实际上是什么

  

[...] 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 = "|")))

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