在使用制表器和pdftools从pdf中提取信息时,我有时希望基于正则表达式模式匹配来索引大量的df。
a <- data.frame(yes=c("pension"))
b <- data.frame(no=c("other"))
my_list <- list(a,b)我想使用str_detect返回与模式“养老金”匹配的底层df的索引。
期望的输出将是:
index <- 1 (based on which and str_detect)
new_list <- my_list[[index]]
new_list
yes
1 pension如何检测底层df中的模式,然后使用它返回索引一直是一个难题。我看到之前使用循环和if-then语句的讨论,但使用purrr的解决方案似乎更可取。
发布于 2018-12-24 00:07:14
我们可以使用
getIdx <- function(pattern, l)
l %>% map_lgl(~ any(unlist(map(.x, grepl, pattern = pattern))))
getIdx("pension", my_list)
# [1] TRUE FALSE
my_list[getIdx("pension", my_list)]
# [[1]]
# yes
# 1 pension这允许多个匹配的数据帧。(真的不需要which。)
在getIdx中,我们遍历l的数据帧,然后在给定的数据帧中遍历其列并使用grepl。如果在任何列中存在匹配项,则为相应的数据帧返回TRUE。
https://stackoverflow.com/questions/53904925
复制相似问题