3

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")
Spacedman
  • 92,590
  • 12
  • 140
  • 224
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
  • @Paul John, I do not pass the function directly but a variable containing the function. However, I am terribly afraid that my problem has no solution. – Colonel Beauvel Dec 12 '14 at 15:48
  • 2
    Gah, I keep confusing myself. @JohnPaul That solution won't work. As I originally attempted to say (and I think I was right) I don't think there is way to do this. The solution is to create a named vector in the first place. – joran Dec 12 '14 at 15:49
  • @joran You are right. It seems that the `funcs` vector does not automatically store the function names in any way. – John Paul Dec 12 '14 at 15:57
  • 2
    As the other comments suggest, only the function itself is stored, not the named object, when you do `c(func1,...)` . – Carl Witthoft Dec 12 '14 at 16:11
  • This question might be relevant: http://stackoverflow.com/questions/25621108/keeping-function-names-when-stored-in-an-object/25621265#25621265 – nicola Dec 12 '14 at 16:48

2 Answers2

1

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)
jafelds
  • 894
  • 8
  • 12
1

How about this approach:

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

 do.call(flist[1],list(5))
# 5
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73