Check if column contains value from a list and assign that value to new column

和自甴很熟 提交于 2021-01-28 09:42:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/58163422/check-if-column-contains-value-from-a-list-and-assign-that-value-to-new-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!