Sowmya S. Manian Sowmya S. Manian - 2 months ago 7
Perl Question

Searching functions using grep over multiple loaded packages in R

Lets say I have package

base
,
dplyr
,
data.table
,
tidyr
etc. loaded using
sapply()
.

sapply(c("dplyr","data.table","tidyr"),library,character.only=TRUE)


So to check the list of functions in a particular package I do

ls("package:data.table")


Now if I want to search for functions inside
dplyr
starting with
is.
pattern I do

grep("is\\.",ls("package:dplyr"),value=TRUE)
# [1] "is.grouped_df" "is.ident" "is.sql" "is.src"
# [5] "is.tbl"


My Goal is to search for all the functions starting with
is.
or
as.
or any other pattern in multiple packages simultaneously. The code I think would be lengthy i.e. below I have combined list of
dplyr
and
base
functions and then added grep pattern. How to do it for many loaded packages?

grep("is\\.",c(ls("package:dplyr"),ls("package:base")),value=T)


Function
search()
would give me list of loaded packages. But how to gather all the functions of loaded packages, so that I can later
grep
on it.

For a single package, list of functions can be obtained by

ls("package:package_name")


Any help is highly appreciated.

Answer

To get a list of all packages which are loaded, use:

x <- grep('package:',search(),value=TRUE)  # Comment below by danielson
# e.g. ("package:base", "package:data.table")

sapply(x, function(x) {
    paste0(x, ":", grep("is\\.", ls(x),value=TRUE))
})

Output:

$`package:base`
 [1] "package:base:is.array"              "package:base:is.atomic"
 [3] "package:base:is.call"               "package:base:is.character"
 [5] "package:base:is.complex"            "package:base:is.data.frame"
 [7] "package:base:is.double"             "package:base:is.element"
 ...

$`package:data.table`
[1] "package:data.table:is.data.table"