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
相关文章推荐
- JavaSE8基础 多态扩展性 父类引用作为函数参数,调用所装子类对象的重写方法
- 字符串使用&&引用对象作为函数参数
- 对象作为函数参数时调用拷贝构造函数、引用做函数参数时只是传递地址
- 函数:引用file类对象及io类对象作为参数打印文本及显示文本
- 对象作为函数参数时调用拷贝构造函数、引用做函数参数时只是传递地址
- JavaSE8基础 抽象类的引用作为函数的参数 指向的一定是子类的对象
- 【C++】对象作为函数参数【原创技术】
- 今天才搞清楚:原来在C#中对象作函数参数,是引用传递:)
- 对象作为函数参数、类外定义成员函数
- C# 引用类型作为函数参数时
- 【C++】对象作为函数参数【原创技术】
- C++结构体作为函数参数(值和引用)和返回值
- C# 引用类型作为函数参数时
- 学习android JNI的那些事儿--------6. 在java中传入引用数据类型(对象)作为参数
- CPen 对象不能作为函数的参数
- 将对象作为参数传递给成员函数
- .net中引用传递对象作为参数传递的问题
- 函数形参参数:const对象,const指针 const引用 实例
- C++ 引用和指针作为函数参数的例子。请不要拍砖
- CComPtr对象作为参数进行 1.值传递 2.引用传递 3.做为返回值的注意事项