[英]Match multiple substrings from another list of all possible substrings in R
[英]R - how to loop through a dataframe to match multiple substrings - concatenate all matches in a new column
我對R很陌生 - 整天都在努力,但我沒有想法。
我在一列中有一個包含長描述的數據框,例如: df
:
ID Name Description
1 A ABC DEF
2 B ARS XUY
3 C ASD
我有一個搜索詞矢量:
ABC
ARS
XUY
DE
我想瀏覽數據框中的每一行,並搜索任何搜索項的Description
。 然后我希望所有匹配在數據幀的新列中連接,例如:
ID Name Description Matches
1 A ABC DEF ABC
2 B ARS XUY ARS;XUY
3 C ASD
我想用1000個搜索詞來搜索~100k行。 有沒有人有任何想法? 我能夠得到一個帶有sapply
和grepl
的矩陣,但我寧願有一個連接的解決方案。
使用strsplit
和%in%
而不是正則表達式的一個選項:
df$Matches <- sapply(strsplit(as.character(df$Description), '\\s'),
function(x){paste(search[search %in% x], collapse = ';')})
df
# ID Name Description Matches
# 1 1 A ABC DEF ABC
# 2 2 B ARS XUY ARS;XUY
# 3 3 C ASD
search <- c("ABC", "ARS", "XUY", "DE")
df <- structure(list(ID = 1:3, Name = structure(1:3, .Label = c("A",
"B", "C"), class = "factor"), Description = structure(1:3, .Label = c("ABC DEF",
"ARS XUY", "ASD"), class = "factor"), Matches = c("ABC", "ARS;XUY",
"")), .Names = c("ID", "Name", "Description", "Matches"), row.names = c(NA,
-3L), class = "data.frame")
我在注釋中嘗試使用的另一個選項是使用stringr
包。 這種方法有兩個潛在的缺點:1)它使用正則表達式,2)它返回匹配的搜索詞而不是找到的值。
library(stringr)
df = data.frame(Name=LETTERS[1:3],
Description=c("ABC DEF", "ARS XUY", "ASD"),
stringsAsFactors=F)
search_terms = c("ABC", "ARS", "XUY", "DE")
regex = paste(search_terms, collapse="|")
df$Matches = sapply(str_extract_all(df$Description, regex), function(x) paste(x, collapse=";"))
df
# Name Description Matches
# (chr) (chr) (chr)
# 1 A ABC DEF ABC;DE
# 2 B ARS XUY ARS;XUY
# 3 C ASD
話雖如此,我認為Alistaire的解決方案是更好的方法,因為它不使用正則表達式。
這是另一種選擇:
df <- data.frame(ID=c(1L,2L,3L),Name=c('A','B','C'),Description=c('ABC DEF','ARS XUY','ASD'),stringsAsFactors=F);
st <- c('ABC','ARS','XUY','DE');
df$Matches <- apply(sapply(paste0('\\b',st,'\\b'),grepl,df$Description),1L,function(m) paste(collapse=';',st[m]));
df;
## ID Name Description Matches
## 1 1 A ABC DEF ABC
## 2 2 B ARS XUY ARS;XUY
## 3 3 C ASD
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.