Creating a list of all functions in a library

I recently learned how to find out the names of all the functions in a library in R:

For example:

#load desired library
library(ParBayesianOptimization)

#find out all functions from this library
getNamespaceExports("ParBayesianOptimization")

[1] "addIterations"    "getLocalOptimums" "bayesOpt"         "getBestPars"      "changeSaveFile"   "updateGP" 

The above code tells me the name of all functions that are used in the "ParBayesianOptimization" library. From here, I could manually inspect each one of these functions - for example:

# manually inspect any one of these functions
getAnywhere(bayesOpt)

A single object matching ‘bayesOpt’ was found
It was found in the following places
  package:ParBayesianOptimization
  namespace:ParBayesianOptimization
with value

#function stats here
function (FUN, bounds, saveFile = NULL, initGrid, initPoints = 4, 
    iters.n = 3, iters.k = 1, otherHalting = list(timeLimit = Inf, 
        minUtility = 0), acq = "ucb", kappa = 2.576, eps = 0, 
    parallel = FALSE, gsPoints = pmax(100, length(bounds)^3), 
    convThresh = 1e+08, acqThresh = 1, errorHandling = "stop", 
    plotProgress = FALSE, verbose = 1, ...) 
{
    startT <- Sys.time()
    optObj <- list() 

etc etc etc ...

saveFile = saveFile, verbose = verbose, ...)
    return(optObj)
}
#function ends here
<bytecode: 0x000001cbb4145db0>
<environment: namespace:ParBayesianOptimization>

Goal : Is it possible to take each one of these functions and create a notepad file with their full definitions?

Something that would look like this:

enter image description here

My attempt:

I thought I could first make an "object" in R that contained all the functions found in this library:

library(plyr)
a = getNamespaceExports("ParBayesianOptimization")
my_list = do.call("rbind.fill", lapply(a, as.data.frame))

            X[[i]]
1    addIterations
2 getLocalOptimums
3         bayesOpt
4      getBestPars
5   changeSaveFile
6         updateGP

Then, I could manually create an "assignment arrow":

header_text <- rep("<-")

Then, "paste" this to each function name:

combined_list <- as.character(paste(my_list, header_text, sep = ""))

But this is not looking correct:

combined_list
[1] "c(\"addIterations\", \"getLocalOptimums\", \"bayesOpt\", \"getBestPars\", \"changeSaveFile\", \"updateGP\")<- "

The goal is to automate the process of manually copying/pasting :

function_1 = getAnywhere("first function ParBayesianOptimization library") 
function_2 = getAnywhere("second function ParBayesianOptimization library") 
etc

final_list = c(function_1, function_2 ...)

And removing the generic description from each function:

A single object matching ‘bayesOpt’ was found
It was found in the following places
  package:ParBayesianOptimization
  namespace:ParBayesianOptimization
with value

In the end, if I were to "call" the final_list object, all the functions from this library should get recreated and reassigned.

Can someone please show me how to do this? Thanks

Hi there,

I don't know why you want to do this, but it was a fun little challenge :slight_smile:
Here is my code using a few functions from the base package as an example

lib = "base"

#List all functions in pakcage
functionNames = getNamespaceExports(lib)

#Extract name and function code (here limited to 10 functions)
functions = lapply(functionNames[100:109], function(fn){
  fn = getAnywhere(fn)
  list(name = fn$name, fn = fn$objs[[1]])
})

#Paste everything together 
functions = paste("# --- FUNCTION", 1:length(functions), ":", 
      sapply(functions, "[[", 1), "\n",
      sapply(lapply(sapply(functions, "[[", 2), capture.output), paste, collapse = "\n"),
      "\n\n# --- END FUNCTION",1:length(functions), "\n\n")

#Write the file
writeLines(functions, "functions.txt")

Example output

# --- FUNCTION 1 : match 
 function (x, table, nomatch = NA_integer_, incomparables = NULL) 
.Internal(match(x, table, nomatch, incomparables))
<bytecode: 0x000001a886f9be70>
<environment: namespace:base> 

# --- END FUNCTION 1 


# --- FUNCTION 2 : order 
 function (..., na.last = TRUE, decreasing = FALSE, method = c("auto", 
    "shell", "radix")) 
{
    z <- list(...)
    decreasing <- as.logical(decreasing)
    if (length(z) == 1L && is.numeric(x <- z[[1L]]) && !is.object(x) && 
        length(x) > 0) {
        if (.Internal(sorted_fpass(x, decreasing, na.last))) 
            return(seq_along(x))
    }
    method <- match.arg(method)
    if (any(vapply(z, is.object, logical(1L)))) {
        z <- lapply(z, function(x) if (is.object(x)) 
            as.vector(xtfrm(x))
        else x)
        return(do.call("order", c(z, list(na.last = na.last, 
            decreasing = decreasing, method = method))))
    }
    if (method == "auto") {
        useRadix <- all(vapply(z, function(x) {
            (is.numeric(x) || is.factor(x) || is.logical(x)) && 
                is.integer(length(x))
        }, logical(1L)))
        method <- if (useRadix) 
            "radix"
        else "shell"
    }
    if (method != "radix" && !is.na(na.last)) {
        return(.Internal(order(na.last, decreasing, ...)))
    }
    if (method == "radix") {
        decreasing <- rep_len(as.logical(decreasing), length(z))
        return(.Internal(radixsort(na.last, decreasing, FALSE, 
            TRUE, ...)))
    }
    if (any(diff((l.z <- lengths(z)) != 0L))) 
        stop("argument lengths differ")
    na <- vapply(z, is.na, rep.int(NA, l.z[1L]))
    ok <- if (is.matrix(na)) 
        rowSums(na) == 0L
    else !any(na)
    if (all(!ok)) 
        return(integer())
    z[[1L]][!ok] <- NA
    ans <- do.call("order", c(z, list(decreasing = decreasing)))
    ans[ok[ans]]
}
<bytecode: 0x000001a885c92778>
<environment: namespace:base> 

# --- END FUNCTION 2 
 
...

The trick was using a bunch of apply statements to extract all the data needed and paste it together. The capture.output function was the most important one as this saved the output printed to the console when viewing a function in text format

Hope this helps,
PJ

2 Likes

Thank you so much for your answer!

I think I found a much easier way to do this:

pkg <- "insert the name of the library you want"
dump(getNamespaceExports(pkg), file="funs_mco.R", envir = asNamespace(pkg))

This automatically creates a "rds.file" on your computer with a list of all the functions from the library!

Please be aware of our cross-posting policy, this is not allowed.

sorry! i did not know that - I will remove it

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.