Reputation: 31161
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")
Upvotes: 3
Views: 93
Reputation: 21492
How about this approach:
flist<-ls(patt='func*')
flist[1]
[1] "func1"
do.call(flist[1],list(5))
# 5
Upvotes: 1
Reputation: 952
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)
Upvotes: 1