R中用户定义函数的公式

时间:2021-02-15 12:56:26

Formulas are a very useful feature of R's statistical and graphical functions. Like everyone, I am a user of these functions. However, I have never written a function that takes a formula object as an argument. I was wondering if someone could help me, by either linking to a readable introduction to this side of R programming, or by giving a self-contained example.

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

1 个解决方案

#1


6  

You can use model.matrix() and model.frame() to evaluate the formula:

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

which yields

产量

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


6  

You can use model.matrix() and model.frame() to evaluate the formula:

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

which yields

产量

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