【发布时间】:2018-03-09 10:55:41
【问题描述】:
我有一个包含两列 specialty 和 keywords 的数据框。如果在search terms 与列specialty 中的任何值之间找到匹配项,我使用以下代码从列keywords 中提取值:
speciality <- c("Emergency medicine","Allergology","Anesthesiology","Hematology","Cardiology")
keywords <- c("emergency room OR emergency medicine OR emergency department",
"Allergy OR rhinitis OR asthma OR atopic eczema",
"Pain OR local anaesthesia OR general anaesthesia OR induced sleep",
"Anemia OR bleeding disorders OR hemophilia OR blood cancers",
"Heart OR cardiac diseases OR Cardiomyopathy OR Congenital Heart Disease OR Cardiac Arrhythmia")
sample <- data.frame(speciality, keywords)
keyspecial <- "Allergology"
subkeywords <- subset(sample$keywords, sample$speciality==keyspecial)
View(subkeywords)
所以我在speciality 列中搜索Allergology。一旦我运行我得到的代码
Allergy OR rhinitis OR asthma OR atopic eczema
我面临的问题是,如果我搜索 allergology 而不是 Allergology,我不会得到结果。或者,如果我只想使用 emergency 而不是 Emergency medicine 进行搜索。
有什么建议吗?
【问题讨论】:
-
您只需要一点正则表达式 - 对于您提到的情况,尝试类似
subkeywords <- subset(sample$keywords, grepl("[Aa]llerg",sample$speciality))的内容 - 这将获取包含Allerg或allerg的任何内容。 -
您可能对一个搜索词“过敏症”是正确的。但我的观点是,搜索词每次都会改变,因此,代码应该负责找到这些词,而不考虑案例和部分匹配。
-
grepl将涵盖部分匹配问题。对于大写,您可以使用tolower将所有内容转换为小写。所以subkeywords <- subset(sample$keywords, grepl(tolower(keyspecial),tolower(sample$speciality)))。或者您可以在grepl中使用ignore.case=TRUE。