4

我有一个公式列表,我使用lapplyandlm创建一个回归模型列表。但是,当我查看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))

然后检查calltemp_fm_list[[2]]

temp_fm_list[[2]]$call

lm(formula = x, data = mtcars)

当我希望它明确给出

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

1 回答 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  
于 2013-04-02T01:01:54.957 回答