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:
我使用sapply对每个函数进行循环,我想找到一个函数命令来检索函数的名称:
res=sapply(funcs, function(f){
command(f)
})
So that res
is then:
所以res是:
c("func1","func2","func3")
2 个解决方案
#1
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:
虽然如果用c创建了function,则无法获得名称,但这里有一个方便的函数来创建保留名称的function:
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)
#2
1
How about this approach:
这个方法:
flist<-ls(patt='func*')
flist[1]
[1] "func1"
do.call(flist[1],list(5))
# 5
#1
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:
虽然如果用c创建了function,则无法获得名称,但这里有一个方便的函数来创建保留名称的function:
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)
#2
1
How about this approach:
这个方法:
flist<-ls(patt='func*')
flist[1]
[1] "func1"
do.call(flist[1],list(5))
# 5