有没有一种方法可以使用作为 R 中数据框中列中的元素的运算符

Is there a way to use operators that are elements in a column in a data frame in R

实际目标比这要广泛得多,但就在这中间,我需要执行方程式,其中运算符是数据框中的值之一。示例代码从正在使用的 df 中复制三列的格式。在此示例 df 中,我想执行操作 20+5、10-10 和 5*15。

# R code for sample df
a <- c(20,10,5)
b <- as.character(c("+","-","*"))
c <- c(5,10,15)
df <- data.frame(a,b,c)

使用 dplyr 的一种相当明确的方法可能是:

df %>%
 mutate(d = case_when(b == "+" ~ a + c,
                      b == "-" ~ a - c,
                      TRUE ~ a * c))

在这里你基本上定义了关系。因为运营商不多,问题不大。

@Gregor 已经概述的另一种方式涉及 eval(parse(...)):

df %>%
 rowwise() %>%
 mutate(d = paste(a, b, c),
        d = eval(parse(text = d)))

但是,请谨慎使用。参见 What specifically are the dangers of eval(parse(…))?

sapply(with(df, paste(a, b, c)), function(x) eval(parse(text = x)))
 20 + 5 10 - 10  5 * 15 
     25       0      75 

但要小心!当你走这条路时,事情会变得非常混乱。脆弱,难以调试。

如果您只是使用简单的原始二进制操作数,您可以获取函数并将它们应用于值。例如

with(df, mapply(function(op,x,y) {op(x, y)}, 
  mget(as.character(b), inherits=TRUE), a, c))

这里我们使用mget()获取每个运算符的函数,然后使用mapply()将其他列作为参数传递。