在R中用户定义的函数中的公式

11

公式是R的统计和图形功能非常有用的特性。像大多数人一样,我也是这些函数的用户。然而,我从未编写过以公式对象作为参数的函数。我想知道是否有人可以帮助我,要么通过提供可读的介绍R编程这一方面的链接,要么通过给出自包含的示例。

1个回答

7
您可以使用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

1
谢谢,非常有趣。我也理解为什么glmnet或其他包可能不提供这种功能:它在Matrix包中使用稀疏矩阵,可能无法使用model.matrix()处理。 - gappy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接