Reputation: 1987
I'd like to take the following "eq" function and improve it in two ways:
So it can run for any number of coefficients
So it will make the variables display without the matrix portion i.e. like this:
y == 0.29 + 0.18 * "b" + 0.4 * "c"
my code:
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"
Upvotes: 2
Views: 63
Reputation: 32466
You could do it using some paste
and parse
I was trying originally to deal with the possibility of no intercept, but it got too confusing with the possibility of factor/non-factor variables, so this just assumes the intercept.
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)
Upvotes: 2