受到这个答案中提供的方程风格的启发,一个更通用的方法(多个预测器+ latex输出作为选项)可以是:
print_equation= function(model, latex= FALSE, ...){
dots <- list(...)
cc= model$coefficients
var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
var_sign[var_sign==""]= ' + '
f_args_abs= f_args= dots
f_args$x= cc
f_args_abs$x= abs(cc)
cc_= do.call(format, args= f_args)
cc_abs= do.call(format, args= f_args_abs)
pred_vars=
cc_abs%>%
paste(., x_vars, sep= star)%>%
paste(var_sign,.)%>%paste(., collapse= "")
if(latex){
star= " \\cdot "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
paste0("\\hat{",.,"_{i}}")
x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
}else{
star= " * "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]
x_vars= names(cc_)[-1]
}
equ= paste(y_var,"=",cc_[1],pred_vars)
if(latex){
equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
}
cat(equ)
}
model参数需要一个lm对象,latex参数是一个布尔值,要求一个简单的字符或一个乳胶格式的方程,而…参数将其值传递给format函数。
我还添加了一个选项来输出它为latex,这样你就可以在rmarkdown中使用这个函数:
```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```
现在使用它:
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)
print_equation(model = lm_mod, latex = FALSE)
这段代码产生:
Y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z
如果我们要求一个乳胶方程,将参数四舍五入为3位:
print_equation(model = lm_mod, latex = TRUE, digits= 3)
这个收益率: