简体   繁体   中英

Get the name of a function contained in variable

Certainly a very basic question but I do not have the answer:

I have a vector of function:

func1 <- function(u) u
func2 <- function(u) NA
func3 <- function(u) 1

funcs = c(func1, func2, func3)

I loop over every function using sapply , and I want to find a function command that retrieves the name of the function:

res=sapply(funcs, function(f){
    command(f)
})

So that res is then:

c("func1","func2","func3")

Although there is no way to get the names if funcs is created with c, here is a convenience function for creating funcs that preserves the names:

cn <- function(...)
{
      # call c() on parameters supplied, adding names
      cnames <- sapply(as.list(substitute(list(...)))[-1L],as.character)
      out <- c(...)
      names(out) <- cnames
      return(out)
}
funcs = cn(func1, func2, func3)

How about this approach:

 flist<-ls(patt='func*')
 flist[1]
[1] "func1"

 do.call(flist[1],list(5))
# 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM