[英]Partial string match two columns R
我一直在嘗試基於兩列共有的正則表達式列表來部分匹配兩列內容:
dats<-data.frame(ID=c(1:3),species=c("dog","cat","rabbit"),
species.descriptor=c("all animal dog","all animal cat","rabbit exotic"),product=c(1,2,3),
product.authorise=c("all animal dog cat rabbit","cat horse pig","dog cat"))
為了實現這一目標:
goal<-data.frame(ID=c(1:3),species=c("dog","cat","rabbit"),
species.descriptor=c("all animal dog","all animal cat","rabbit exotic"),
product=c(1,2,3),product.authorise=c("all animal dog cat rabbit","cat horse pig",
"dog cat"), authorised=c("TRUE","TRUE","FALSE"))
所以為了進一步解釋,如果'dog'出現在兩列中的任何一點,那么在$ match中這將被視為'TRUE' - 這將適用於任何單個物種描述符。如果沒有找到匹配,那么返回FALSE或na會沒事的。
到目前為止,我已經達到了這一點:
library(stringr)
patts<-c("dog","cat","all animal")
reg.patts<-paste(patts,collapse="|")
dats$matched<-ifelse((str_extract(dats$species.descriptor,reg.patts) == str_extract(dats$product.authorise,reg.patts)),"TRUE","FALSE")
dats
ID species species.descriptor product product.authorise matched
1 dog all animal dog 1 all animal dog cat rabbit TRUE
2 cat all animal cat 2 cat horse pig FALSE
3 rabbit rabbit exotic 3 dog cat <NA>
正如您所看到的,這正確地標識了第一行和最后一行,因為“所有動物”在兩個字符串中首先出現,並且在最后一行中根本沒有匹配。 但是,當reg exp沒有首先出現在字符串中時,似乎很難(如第二行)。 我已經嘗試過str_extract_all,但到目前為止只導致錯誤消息。 我想知道是否有人可以提供幫助,拜托?
這是使用dplyr
進行管道處理的解決方案。 芯組分是使用grepl
為邏輯字符串匹配species
中都species.descriptor
和product.authorised
。
library(dplyr)
dats %>%
rowwise() %>%
mutate(authorised =
grepl(species, species.descriptor) &
grepl(species, product.authorise)
)
Source: local data frame [3 x 6]
Groups: <by row>
ID species species.descriptor product product.authorise authorised
(int) (fctr) (fctr) (dbl) (fctr) (lgl)
1 1 dog all animal dog 1 all animal dog cat rabbit TRUE
2 2 cat all animal cat 2 cat horse pig TRUE
3 3 rabbit rabbit exotic 3 dog cat FALSE
如果你真的喜歡stringr
你可以使用str_detect
函數獲得更加用戶友好的語法。
library(stringr)
dats %>%
mutate(authorised =
str_detect(species.descriptor, species) &
str_detect(product.authorise, species)
)
如果您不喜歡dplyr
,可以直接添加列
dats$authorised <-
with(dats,
str_detect(species.descriptor, species) &
str_detect(product.authorise, species)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.