有没有一种方法可以得到一个包含所有函数的列表,这些函数的名称与给定的正则表达式匹配?

时间:2021-12-07 20:28:05

I would like to get a list of all functions which name match a given pattern. For instance, I would like to have all functions which name includes "theme_".

我想要得到一个与给定模式匹配的所有函数的列表。例如,我希望所有的函数都包含“theme_”。

I've seen this post which gives a solution to get a vector of names. Is it possible to have the same as a list of functions instead of a vector of names ?

我已经看到了这篇文章,它给出了一个得到一个名字向量的解。是否有可能拥有相同的函数列表而不是名称向量?

1 个解决方案

#1


4  

For local packages you might try this:

对于本地包,您可以尝试以下方法:

if (!require("pacman")) install.packages("pacman"); library(pacman)

regex <- "theme_"
packs <- p_lib()

out <- setNames(lapply(packs, function(x){
    funs <- try(p_funs(x, character.only=TRUE))
    if (inherits(funs, "try-error")) return(character(0))
    funs[grepl(regex, funs)]
}), packs)

out[!sapply(out, identical, character(0))]

Here's my output:

这是我的输出:

## $cowplot
## [1] "theme_cowplot" "theme_nothing"
## 
## $ggplot2
##  [1] "theme_blank"    "theme_bw"       "theme_classic"  "theme_get"      "theme_gray"     "theme_grey"     "theme_light"    "theme_line"     "theme_linedraw" "theme_minimal" 
## [11] "theme_rect"     "theme_segment"  "theme_set"      "theme_text"     "theme_update"  
## 
## $gridExtra
## [1] "ttheme_default" "ttheme_minimal"
## 
## $plotflow
## [1] "theme_apa"   "theme_basic" "theme_black" "theme_map"  
## 
## $qdap
## [1] "theme_badkitchen" "theme_cafe"       "theme_duskheat"   "theme_grayscale"  "theme_greyscale"  "theme_hipster"    "theme_nightheat"  "theme_norah"     

#1


4  

For local packages you might try this:

对于本地包,您可以尝试以下方法:

if (!require("pacman")) install.packages("pacman"); library(pacman)

regex <- "theme_"
packs <- p_lib()

out <- setNames(lapply(packs, function(x){
    funs <- try(p_funs(x, character.only=TRUE))
    if (inherits(funs, "try-error")) return(character(0))
    funs[grepl(regex, funs)]
}), packs)

out[!sapply(out, identical, character(0))]

Here's my output:

这是我的输出:

## $cowplot
## [1] "theme_cowplot" "theme_nothing"
## 
## $ggplot2
##  [1] "theme_blank"    "theme_bw"       "theme_classic"  "theme_get"      "theme_gray"     "theme_grey"     "theme_light"    "theme_line"     "theme_linedraw" "theme_minimal" 
## [11] "theme_rect"     "theme_segment"  "theme_set"      "theme_text"     "theme_update"  
## 
## $gridExtra
## [1] "ttheme_default" "ttheme_minimal"
## 
## $plotflow
## [1] "theme_apa"   "theme_basic" "theme_black" "theme_map"  
## 
## $qdap
## [1] "theme_badkitchen" "theme_cafe"       "theme_duskheat"   "theme_grayscale"  "theme_greyscale"  "theme_hipster"    "theme_nightheat"  "theme_norah"