我有一個國家名稱串列和一個包含一列文本和一列二進制指標的資料框。
MWE:
rm(list=ls())
library(countrycode)
country_list <- countrycode::codelist$country.name.en
Text <- c("This is","a test to", "find country", "names like Algeria", "Albania and Afghanistan","in the data","and return only the","first match in each","string, Algeria and Albania", "not Afghanistan")
df <- as.data.frame(Text)
df$ofInterest <- c(0,0,0,1,1,1,0,0,1,0)
我想回傳df$Text匹配中任何元素的第一個單詞(并且只有第一個單詞) country_list。換句話說,我只對提到的第一個國家名稱感興趣。
該操作應為每一行創建一個新列來df指示匹配的國家名稱,如果沒有找到匹配的國家名稱,則為NA 。country_list
為了讓事情變得更快,我還想將搜索限制在df$ofInterest==1.
換句話說,它應該回傳以下內容:
Text ofInterest Match
This is 0 NA
a test to 0 NA
find country 0 NA
names like Algeria 1 Algeria
Albania and Afghanistan 1 Albania
in the data 1 NA
and return only the 0 NA
first match in each 0 NA
string, Algeria and Albania 1 Algeria
not Afghanistan 0 Afghanistan
我的問題是我不知道如何使用正則運算式,同時還從串列中進行模式匹配。我怎樣才能在 R 中做到這一點?
這是我所能得到的。“ xxxxx ”大概是country_name串列應該去的地方。
這可能是一個簡單的問題,但我找不到解決方案。感謝您的任何幫助!
df$Match <- ifelse(str_extract(df$Text, "(?<=^| )xxxxx.*?(?=$| )") %in% country_list, str_extract(df$Text, "(?<=^| )xxxxx.*?(?=$| )"), NA)
uj5u.com熱心網友回復:
您可以使用
df$Match <- str_extract(df$Text, paste0("(?i)\\b(", paste(country_list, collapse="|"), ")\\b"))
df <- within(df, Match[ofInterest == '0'] <- NA)
# > df
# Text ofInterest Match
# 1 This is 0 <NA>
# 2 a test to 0 <NA>
# 3 find country 0 <NA>
# 4 names like Algeria 1 Algeria
# 5 Albania and Afghanistan 1 Albania
# 6 in the data 1 <NA>
# 7 and return only the 0 <NA>
# 8 first match in each 0 <NA>
# 9 string, Algeria and Albania 1 Algeria
# 10 not Afghanistan 0 <NA>
在這里,paste0("(?i)\\b(", paste(country_list, collapse="|"), ")\\b")將創建一個像
(?i)- 不區分大小寫的匹配\b- 單詞邊界(- 捕獲組的開始:paste(country_list, collapse="|")將產生一個以|- 分隔的國家名稱串列,例如Albania|Poland|France等。
)- 小組結束\b- 單詞邊界。
將在columnn 值為的所有行中df <- within(df, Match[ofInterest == '0'] <- NA)恢復。NAMatchofInterest0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418383.html
標籤:
