Get the name of the function contained in a variable

Of course, a very simple question, but I have no answer:

I have a vector of a function:

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

funcs = c(func1, func2, func3)

      

I iterate over each function with sapply

and I want to find a function command

that retrieves the function name:

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

      

So res

:

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

      

+3


source to share


2 answers


While there is no way to get names if func is created with c, here is a handy function for creating funcs that preserves 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)

      

+1


source


How about this approach:



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

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

      

+1


source







All Articles