如何将公式转换为函数,或将公式应用于某些值?

How to convert formula to function, or apply the formula to some values?

我有一个函数 需要 期望 formula 作为输入,例如 y~x 的形式。然后,我需要将一系列 x-values 传递到该公式中以得出 y

例如,如果我的公式是 y~x^2,我的 x 值系列是 (1,2,3,4),那么我应该期望 (1,4,9,16) 为输出。

假设我有这样的公式:formula1 <- y~x:

这是我迄今为止尝试过的方法:

像这样:

formula1 <- y~x^2 
x <- c(1,2,3,4)
my_data <- data.frame("x" = x, "y" = rep(0,length(x))) 
model_frame <- model.frame(formula1, data = my_data)
my_design_matrix <- model.matrix(formula1, model_frame)

这有什么用?

以下是我查阅的资源:
How to apply a formula to a vector in R?

Pass formula to function in R?

我不确定这是否是最优雅的方式,但它应该可以满足您的要求:

想法是提取公式对象的右侧并将其解析为字符串。然后可以评估结果。

as.function <- function(formula) {
    cmd <- tail(as.character(formula),1)
    exp <- parse(text=cmd)
    function(...) eval(exp, list(...))
}

但请注意,有些有效公式可能无法以这种方式计算,例如 y ~ a:c

这给了我们

> f <- as.function(y ~ x^2)
> f(x=1:10)
 [1]   1   4   9  16  25  36  49  64  81 100

如果您想向生成的函数提交 data.frame,您可以这样做

as.function <- function(formula) {
    cmd <- tail(as.character(formula),1)
    exp <- parse(text=cmd)
    function(df) eval(exp, df)
}

并获得

> f <- as.function(y ~ x^2)
> f(data.frame(x=1:10))
 [1]   1   4   9  16  25  36  49  64  81 100