如何解决如何在 R 数据框中的不同字符串列中找到一组精确的字符串?
我希望在包含字符串的 R 数据帧列中找到一组精确匹配的字符串。
这是我的一堆参考字符串的格式,这些字符串将存储在变量 splitval
中:
library(gsubfn)
#Splitting each rule into its individual parameter elements
str <- strsplit(gsub("\\,\\+"," +",gsub("=>","",gsubfn(".",list("{" = "","}" = ""),gsub("corpsi","+corpsi","{dog} => {pet}")))),split='+',fixed=TRUE)
parameters <- data.frame(do.call(rbind,str)) #Creating a df of the split parameters
parameters <- data.frame(t(parameters))
parameters <- parameters[parameters$t.parameters.!="",]
parameters <- trimws(parameters,"r")
#Applying filter on all the parameters of a single rule row
splitval = strsplit(parameters[1],split=' ',fixed=TRUE)
splitval = lapply(list(splitval[[1]]),function(z){ z[z != ""]}) #Eliminating the "" instances
现在,splitval
具有以下值:
[[1]]
[1] "dog" "pet"
现在我的目标是过滤掉以下数据框的所有行条目,其中字符串列的条目同时包含 dog 和 pet 的确切词。
注意:它不应过滤掉包含doganimal pets 或dogsareanimals 和petssss
等短语的字符串这是我的数据框:
df <- data.frame(Srno = 1:5,Description = c("dog is my pet","doganimal pets country","my pet is my dog","dogsareanimals and petssss","a pet dog is great"))
看起来像这样:
因此,我只需要提取中的第 1,3 和 5 行,因为只有这些行包含专有字符串“dog”和“pet”(没有特定顺序)
但是当我使用以下代码时,我得到了数据帧的所有行,因为所有字符串都包含两个引用关键字 - grep 没有达到预期目的。
extract_df <- df[(grep(splitval[[1]][1],df$Description)),]
for(k in 2:length(splitval[[1]]))
{
extract_df <- extract_df[(grep(splitval[[1]][k],]
}
那么谁能帮我在输出提取的数据框中只获取第 1,3 和 5 行?
解决方法
假设 splitval
中可以有很多单词并且其中不会总是有两个固定单词,您可以为每个单词拆分字符串并选择 all
中包含 vec
单词的行}.
在基础 R 中,您可以这样做:
vec <- splitval[[1]]
#For this case
#vec <- c("dog","pet")
subset(df,sapply(strsplit(df$Description,'\\s+'),function(x) all(vec %in% x)))
# Srno Description
#1 1 dog is my pet
#3 3 my pet is my dog
#5 5 a pet dog is great
使用tidyverse
:
library(tidyverse)
df %>% filter(map_lgl(str_split(df$Description,~all(vec %in% .x)))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。