公式是 R 的统计和图形函数的一个非常有用的特性。和大家一样,我也是这些功能的用户。但是,我从未编写过将公式对象作为参数的函数。我想知道是否有人可以通过链接到 R 编程这一方面的可读介绍或提供一个独立的示例来帮助我。
最佳答案
您可以使用 model.matrix()
和 model.frame()
评估公式:
lm1 <- lm(log(Volume) ~ log(Girth) + log(Height), data=trees)
print(lm1)
form <- log(Volume) ~ log(Girth) + log(Height)
# use model.matrix
mm <- model.matrix(form, trees)
lm2 <- lm.fit(as.matrix(mm), log(trees[,"Volume"]))
print(coefficients(lm2))
# use model.frame, need to add intercept by hand
mf <- model.frame(form, trees)
lm3 <- lm.fit(as.matrix(data.frame("Intercept"=1, mf[,-1])), mf[,1])
print(coefficients(lm3))
这产生
Call: lm(formula = log(Volume) ~ log(Girth) + log(Height), data = trees)
Coefficients: (Intercept) log(Girth) log(Height)
-6.63 1.98 1.12
(Intercept) log(Girth) log(Height)
-6.632 1.983 1.117
Intercept log.Girth. log.Height.
-6.632 1.983 1.117
关于r - R 中用户定义函数中的公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1300575/