线性回归中使用的显式公式

4

我有一系列公式,使用lapplylm函数创建了一个回归模型列表。然而,当查看每个线性模型的call组件时,我并没有看到明确的公式,而是看到了我在线性模型中解析的变量名。例如,使用mtcars数据集:

temp_formula_list = list(as.formula(hp~1),as.formula(hp~cyl))
temp_fm_list = lapply(temp_formula_list, function(x) lm(data = mtcars, formula = x))

然后检查 temp_fm_list[[2]]call:

temp_fm_list[[2]]$call

提供

lm(formula = x, data = mtcars)

当我想要明确给出时

lm(formula = hp~cyl, data = mtcars)

do.call在这种情况下非常有用;例如,请参见https://dev59.com/NFvUa4cB1Zd3GeqPyfNv#7668846。 - Aaron left Stack Overflow
谢谢。这看起来几乎和我的问题一样。我猜我应该在lapply中使用do.call("lm",args = list(formula = x, data=mtcars))而不是lm(data = mtcars, formula = x) - Alex
do.call("lm",args = list(formula = x, data= quote(mtcars))) 将按照您的意愿工作。 - mnel
@Alex -- 我已经将这个补充到我的答案中,以保证完整性。 - mnel
1
as.name 也可以使用(而不是 quote);这个信息在我之前链接的答案的评论中。 - Aaron left Stack Overflow
显示剩余3条评论
1个回答

10

您可以使用 bquote 构造调用来对语言进行一些简单的计算。

 temp_fm_list = lapply(temp_formula_list, function(x) {
  lmc <- bquote( lm(data = mtcars, formula = .(x)))
  eval(lmc)                                                      
  })
temp_fm_list
# Call:
#   lm(formula = hp ~ 1, data = mtcars)
# 
# Coefficients:
#   (Intercept)  
# 146.7  
# 
# 
# [[2]]
# 
# Call:
#   lm(formula = hp ~ cyl, data = mtcars)
# 
# Coefficients:
#   (Intercept)          cyl  
# -51.05        31.96  
请提供需要翻译的完整内容。
function(x) do.call('lm', list(formula = x, data = quote(mtcars))

也可以起作用


其他方法...

即使使用您的原始调用,您也可以从与模型关联的terms对象重新创建公式

例如

x <- hp ~ cyl

lmo <- lm(formula = x, data = mtcars)

formula(lmo)
## hp ~ cyl

lmo$call 


# lm(formula = x, data = mtcars)

如果您愿意,可以对这个call对象进行更改(尽管这是相当危险的做法)。

# for example

lmo$call$formula <- x
lmo$call 
##  lm(formula = hp ~ cyl, data = mtcars)

## however you can create rubbish here too
lmo$call$formula <- 'complete garbage'
lmo$call 
## lm(formula = "complete garbage", data = mtcars)

# but, being careful, you could use it appropriately
temp_fm_list = lapply(temp_formula_list, function(x) {
  oo <- lm(data = mtcars, formula = x)
  oo$call$formula <-x
  oo
})

temp_fm_list
# Call:
#   lm(formula = hp ~ 1, data = mtcars)
# 
# Coefficients:
#   (Intercept)  
# 146.7  
# 
# 
# [[2]]
# 
# Call:
#   lm(formula = hp ~ cyl, data = mtcars)
# 
# Coefficients:
#   (Intercept)          cyl  
# -51.05        31.96  

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