如何提供(逻辑)运算符作为函数的参数
How to supply (logical) operators as arguments to function
是否可以提供逻辑(或算术)运算符作为 R 函数的参数。检查 共享主题的 SO 问题。
f1 <- function(a, b) a>b
然后
> f1(1,2)
[1] FALSE
我如何实现一个允许我更改功能测试的运算符,例如
f2 <- function(a, b, operator = c('<', '>', '==')) { ... }
那我要
> f2(1, 2, '<')
[1] TRUE
在 R 中,所有运算符都是函数。所以,你只需要获取运算符函数并调用它即可。
f2 <- function(a, b, operator) getFunction(operator)(a, b)
f2(1, 2, '<')
#[1] TRUE
一种方法是使用 eval(parse(...))
方法,即
f1 <- function(a, b, op){
eval(parse(text = paste0(a, op, b)))
}
f1(1, 2, '<')
#[1] TRUE
f1(3, 3, '==')
#[1] TRUE
f1(3, 4, '==')
#[1] FALSE
还有一个选项:
foo <- function(a, b, operator) {
f <- match.fun(match.arg(operator, choices = c('<', '>', '==')))
f(a,b)
}
foo(1,2, ">")
#[1] FALSE
foo(1,2, "==")
#[1] FALSE
foo(1,2, "+")
# Show Traceback
#
# Rerun with Debug
# Error in match.arg(operator, choices = c("<", ">", "==")) :
# 'arg' should be one of “<”, “>”, “==”
使用 match.arg
可以将其限制为某些功能。 match.fun
然后得到实际的功能。
如果您不需要对某些输入的限制,您可以跳过 match.arg
并只使用 match.fun
。
是否可以提供逻辑(或算术)运算符作为 R 函数的参数。检查
f1 <- function(a, b) a>b
然后
> f1(1,2)
[1] FALSE
我如何实现一个允许我更改功能测试的运算符,例如
f2 <- function(a, b, operator = c('<', '>', '==')) { ... }
那我要
> f2(1, 2, '<')
[1] TRUE
在 R 中,所有运算符都是函数。所以,你只需要获取运算符函数并调用它即可。
f2 <- function(a, b, operator) getFunction(operator)(a, b)
f2(1, 2, '<')
#[1] TRUE
一种方法是使用 eval(parse(...))
方法,即
f1 <- function(a, b, op){
eval(parse(text = paste0(a, op, b)))
}
f1(1, 2, '<')
#[1] TRUE
f1(3, 3, '==')
#[1] TRUE
f1(3, 4, '==')
#[1] FALSE
还有一个选项:
foo <- function(a, b, operator) {
f <- match.fun(match.arg(operator, choices = c('<', '>', '==')))
f(a,b)
}
foo(1,2, ">")
#[1] FALSE
foo(1,2, "==")
#[1] FALSE
foo(1,2, "+")
# Show Traceback
#
# Rerun with Debug
# Error in match.arg(operator, choices = c("<", ">", "==")) :
# 'arg' should be one of “<”, “>”, “==”
使用 match.arg
可以将其限制为某些功能。 match.fun
然后得到实际的功能。
如果您不需要对某些输入的限制,您可以跳过 match.arg
并只使用 match.fun
。