r-grepl,在数据框中搜索模式列表,并注意找到每个模式的行
我希望这是一个我没有看到的简单解决方案…我有一个功能,可以搜索数据帧中的模式列表,然后将输出保存为TSV:r-grepl,在数据框中搜索模式列表,并注意找到每个模式的行,r,grepl,R,Grepl,我希望这是一个我没有看到的简单解决方案…我有一个功能,可以搜索数据帧中的模式列表,然后将输出保存为TSV: dfSubset <- df[apply(df, 1, function(i) any(grepl(paste(my.list, collapse="|"), i))),] write_tsv(dfSubset, "dfSubset.txt", col_names=TRUE) 谢谢您的帮助和建议。试试这个: library(stringr) rgx = paste(my.list,
dfSubset <- df[apply(df, 1, function(i) any(grepl(paste(my.list, collapse="|"), i))),]
write_tsv(dfSubset, "dfSubset.txt", col_names=TRUE)
谢谢您的帮助和建议。试试这个:
library(stringr)
rgx = paste(my.list, collapse='|')
dfSubset$Pattern_found = apply(dfSubset, 1, function(i) str_extract(paste(i, collapse=','), rgx))
> dfSubset
# V1 V2 V3 V4 V5 Pattern_found
# 3 100409 100087 100767 100145 7048 7048
# 4 100682 100583 100336 100895 100719 682
# 7 100252 100024 100829 100813 7078 7078
在您的
dfSubset
上添加base R的想法
ind <- unlist(sapply(my.list, function(i) grep(i, do.call(paste, dfSubset))))
data.frame(dfSubset[as.integer(ind),], Pattern_found = names(ind))
# V1 V2 V3 V4 V5 Pattern_found
#4 100682 100583 100336 100895 100719 682
#3 100409 100087 100767 100145 7048 7048
#7 100252 100024 100829 100813 7078 7078
什么是
SSTI.list
?SSTI.list是一个打字错误,现在改为my.list。我不确定我是否完全理解输出应该是什么样子。添加了所需的输出
library(stringr)
rgx = paste(my.list, collapse='|')
dfSubset$Pattern_found = apply(dfSubset, 1, function(i) str_extract(paste(i, collapse=','), rgx))
> dfSubset
# V1 V2 V3 V4 V5 Pattern_found
# 3 100409 100087 100767 100145 7048 7048
# 4 100682 100583 100336 100895 100719 682
# 7 100252 100024 100829 100813 7078 7078
ind <- unlist(sapply(my.list, function(i) grep(i, do.call(paste, dfSubset))))
data.frame(dfSubset[as.integer(ind),], Pattern_found = names(ind))
# V1 V2 V3 V4 V5 Pattern_found
#4 100682 100583 100336 100895 100719 682
#3 100409 100087 100767 100145 7048 7048
#7 100252 100024 100829 100813 7078 7078
library(stringi)
df$new <- stri_extract_all_regex(do.call(paste, df), paste(my.list, collapse = '|'), simplify = TRUE)[,1]
df[!is.na(df$new),]
# V1 V2 V3 V4 V5 new
#3 100409 100087 100767 100145 7048 7048
#4 100682 100583 100336 100895 100719 682
#7 100252 100024 100829 100813 7078 7078