Is there a way to get a vector with the name of al

2019-01-11 10:26发布

问题:

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?

(I would like to check user entered variables against this vector. We had some unforseen problem with users entering e.g., c as variable names)

UPDATE: I would like to get the function names from all packages currently loaded.

SOLUTION (half way): Based on Joris Meys tip with lsf.str() I came up with the following function that returns a sorted vector with all currently available function names:

getFunctionNames <- function() {
    loaded <- (.packages())
    loaded <- paste("package:", loaded, sep ="")
    return(sort(unlist(lapply(loaded, lsf.str))))
}

Bu,t see also the comments on Joris Meys' post for even better answers.

回答1:

I'd use lsf.str() as a start.

eg : x <- as.character(lsf.str("package:base")) gives you a list of all functions in the base package. You could do add all packages you want to check against. stats and utils come to mind first.

EDIT : Regarding your question about currently loaded packages :

x <- unlist(sapply(search()[-1],function(x)as.character(lsf.str(x)))) see comments

pkgs <- search()
pkgs <- pkgs[grep("package:",pkgs)]
y <- unlist(sapply(pkgs,lsf.str))

does the trick.



回答2:

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)


标签: function r names