Sandro Motyl
Sandro Motyl

Reputation: 139

How to do %like% with a list of strings as parameter in R?

i want to compare the column "name" of a data.table with some names in a list of strings, with the function %like%:

names <- ( "name1", "name2", "name3" )

specific_names <- data_table[name %like% names]

The output:

In grepl(pattern, vector) :
argument 'pattern' has length > 1 and only the first element will be used

But it really works with the first element, so i did a loop to take all the elements:

for(list_name in names){
 specific_names <- data_table[name %like% list_name]
}

In that way the function doesn't return even the %like% of the first element.

What i'm doing wrong and how to get what i expected? Thanks

Upvotes: 1

Views: 860

Answers (1)

James Thomas Durant
James Thomas Durant

Reputation: 305

You need a single character string to pass to %like%. Use paste with collapse to change the vector names to a character string separated with "|" to make it a regular expression. Like this:

names <- c( "name1", "name2", "name3" )
data_table = data.table(name = rep(c( "name1", "name2", "name3", "name4" ),
                        each=3), y=c(1,3,6,7), v=1:12)

specific_names <- data_table[name %like% paste(names, collapse = "|")]
specific_names

##     name y v
## 1: name1 1 1
## 2: name1 3 2
## 3: name1 6 3
## 4: name2 7 4
## 5: name2 1 5
## 6: name2 3 6
## 7: name3 6 7
## 8: name3 7 8
## 9: name3 1 9

Upvotes: 3

Related Questions