显示线性模型方程文本的函数

Function that displays a text for the equation of a linear model

我想采用以下“eq”函数并在两个方面对其进行改进:

  1. 所以它可以运行任意数量的系数

  2. 所以它会在没有矩阵部分的情况下显示变量,即像这样:

    y == 0.29 + 0.18 * "b" + 0.4 * "c"

我的代码:

x=data.frame(runif(12),rep(c('a','b','c'),4))
lm3=lm(x[,1]~x[,2])
eq=function(c){
bquote( y == .(c[1]) + .(c[2]) * .(names(c)[2])
        + .(c[3]) * .(names(c)[3])) }
c=summary(lm3)$coefficients
c=round(c[,1], digits = 2)
c=summary(lm3)$coefficients
c=round(c[,1], digits = 2)

    > eq(c)
    y == 0.29 + 0.18 * "x[, 2]b" + 0.4 * "x[, 2]c"

你可以使用一些 pasteparse

编辑

我最初试图处理没有拦截的可能性,但它与 factor/non-factor 变量的可能性太混淆了,所以这只是假设拦截。

eq <- function(fit, digits=2) {
    vnames <- attr(terms(fit), 'term.labels')
    x <- round(coef(fit), digits)
    ns <- Vectorize(gsub)(vnames, '', names(x), fixed=TRUE)[-1]  # remove intercept
    xx <- as.vector(x)
    vars <- c(xx[1], paste(xx[-1], ns, sep="*"))
    parse(text=paste0("y == ", paste(vars, collapse=" + ")))
}

## data
x <- data.frame(runif(12),rep(c('a','b','c'),4))
lm3 <- lm(x[,1]~x[,2])

eq(lm3, 2)
# expression(y == 0.35 + 0.21*b + 0.26*c)