Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple strings with str_detect R

I want to find multiple strings and put it in a variable, however I keep getting 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") 

None of these worked. Is there another way to do it with str_detect or should i try something else? I want them to show up as in the same column as well.

like image 843
Magick.M Avatar asked Mar 12 '16 19:03

Magick.M


People also ask

How to detect multiple strings in R?

Detect one of the multiple strings in RYou can work with the multiple grepl functions. If you have a lot of patterns that you want to check, then it is better to use grepl with sapply and apply functions. Another approach in the detection of any of the strings is the usage of the OR operator in regex.

Is Str_detect case sensitive?

The str_detect command checks to see if any instance of a pattern occurs in a string. str_detect(fruits, "p") #any occurrence of 'p'? Note that pattern matching is case-sensitive.

How do I find patterns in R?

You can use the str_detect() function from the stringr function R to detect the presence or absence of a certain pattern in a string. This function returns TRUE if the pattern is present in the string or FALSE if it is not.


2 Answers

An even simpler way, in my opinion, for your quite short list of strings you want to find can be:

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

As this is actually what

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

does, as recommended by @penguin before.

For a longer list of strings you want to detect I would first store the single strings into a vector and then use @penguin's approach, e.g.:

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

This has the advantage that you can easily use the vector strings later on as well if you want to or have to.

like image 87
fabilous Avatar answered Oct 17 '22 04:10

fabilous


This is a way to solve this problem:

queries1 <- httpdf %>%    filter(str_detect(payload, paste(c("create", "drop", "select"),collapse = '|'))) 
like image 41
penguin Avatar answered Oct 17 '22 06:10

penguin