问题描述
如何在在R的函数中通过字符串调用别的函数。
以下面为例子:
testFun <- function(Fun){
x <- 1:100
Fun(x)
}
解法
这个问题没什么其实很笨,就是想记录一下。
#1. 直接调用
testFun <- function(Fun){
x <- 1:100
Fun(x)
}
testFun(sum) # 5050
testFun(Fun = function(x) sum(x) + 1) # 5051
#2. do.call
testFun <- function(Fun){
x <- 1:100
do.call(Fun, list(x))
}
testFun(sum) # 5050
testFun(Fun = function(x) sum(x) + 1) # 5051
testFun('sum') # 5050 -- do.call可以根据字符串名称调用函数
#3. eval,parse (字符串声明函数)
testFun <- function(Fun){
x <- 1:100
eval(parse(text = Fun))
}
testFun('sum(x) + 1') # 5051
#4. match.fun
testFun <- function(Fun){
x <- 1:100
Fun <- match.fun(Fun)
Fun(x)
}
testFun(sum) # 5050
testFun('sum') # 5050