如果我有功能f
:
f <- function(a = character(0),
b = character(0),
c = character(0),
condition = "a + b + c") {
if(condition == "a + b + c")
return(union(union(a, b), c))
if(condition == "(a * b) + c")
return(union(intersect(a, b), c))
if(condition == "(a - b) + c")
return(union(setdiff(a, b), c))
if(condition == "(a - b) - c")
return(setdiff(setdiff(a, b), c))
# etc...
}
f(a = c('1', '2', '3'),
b = c('2', '3', '4'),
c = c('3', '4'),
condition = "a + b + c")
#> [1] "1" "2" "3" "4"
f(a = c('1', '2'),
b = c('2', '3'),
c = c('2', '3', '4'),
condition = "(a * b) + c")
#> [1] "2" "3" "4"
f(a = c('1', '2'),
b = c('2', '3'),
c = c('2', '3', '4'),
condition = "(a - b) - c")
#> [1] "1"
如何解决对参数condition
进行编码的问题,该参数应该在输入向量上定义一个集合运算表达式?
在我的示例中,我仅使用简单的字符串来举例说明预期的行为,但是此解决方案无法很好地扩展。我需要使用语言对象(?!)...
我需要一种简单的方法:
答案 0 :(得分:3)
您可以做的只是解析表达式,然后用适当的函数替换+
,-
和*
。然后,您可以撤消该表达式。例如
f <- function(a = character(0),
b = character(0),
c = character(0),
condition = "a + b + c") {
parsed_cond <- parse(text=condition)[[1]]
translated_expr <- do.call("substitute", list(
parsed_cond,
list(`+`=quote(union),
`-`=quote(setdiff),
`*`=quote(intersect))
))
eval(translated_expr)
}
这将返回您在示例中提供的值