Reputation: 2005
I have a list that contains patterns to find. Then I have a data.table in which I want to find if the value contains any ot the patterns then assign that value to a new column:
library(data.table)
library(stringr)
base_patters <- c("pat1","pat2","pat3")
transformations <- data.table(mynames = c("HI_pat1_jo","A2_a4_pat1_LN","pat3_LN")
)
for( patt in base_patters){
transformations[stringr::str_detect(transformations[, mynames], patt), pattern := patt]
}
I have solved (as you see) with a for loop but I am looking for a more efficient way to do it.
Upvotes: 1
Views: 671
Reputation: 388972
Paste the base_patters
together and use str_extract
to extract any pattern present in mynames
.
library(data.table)
library(stringr)
transformations[,pattern := str_extract(mynames,str_c(base_patters,collapse = "|"))]
# mynames pattern
#1: HI_pat1_jo pat1
#2: A2_a4_pat1_LN pat1
#3: pat3_LN pat3
Upvotes: 1