Is there a way to get a vector with the name of all functions that one could use in R?

前端 未结 2 668
孤街浪徒
孤街浪徒 2020-11-30 07:50

I would like to have a call that returns me a vector with the names of all function that I could call in the current R session. Does anybody know how to achieve this?

<
2条回答
  •  有刺的猬
    2020-11-30 08:13

    I asked a similar Q on R-Help many moons ago (2007) and Prof. Brian Ripley provided this as a solution:

    findfuns <- function(x) {
         if(require(x, character.only=TRUE)) {
            env <- paste("package", x, sep=":")
            nm <- ls(env, all=TRUE)
            nm[unlist(lapply(nm, function(n) exists(n, where=env,
                                                   mode="function",
                                                   inherits=FALSE)))]
         } else character(0)
    }
    pkgs <- dir(.Library)
    z <-  lapply(pkgs, findfuns)
    names(z) <- pkgs
    Z <- sort(unique(unlist(z)))
    

    Which gives output like:

    > head(Z)
    [1] "^"        "-"        "-.Date"   "-.POSIXt" ":"        "::"
    

    This was for finding all the functions in packages specified by object pkgs so you can control which packages are loaded/checked against.

    A modified version that work on the currently loaded set of packages would be:

    findfuns2 <- function(pkgs) {
        nm <- ls(pkgs, all = TRUE)
        nm[unlist(lapply(nm, function(n) exists(n, where = pkgs,
                                                mode = "function",
                                                inherits = FALSE)))]
        if(isTRUE(all.equal(length(nm), 0)))
            character(0)
        else
            nm
    }
    
    pkgs <- search()
    pkgs <- pkgs[grep("package:", pkgs)]
    z <- lapply(pkgs, findfuns2)
    z <- sort(unique(unlist(z)))
    head(z)
    

提交回复
热议问题