您的位置:首页 > 其它

R语言-引用函数对象作为参数

2017-03-17 17:41 686 查看

问题描述

如何在在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: