0

I am curious how one would edit the following solution from Jayden so that the equation may be formatted y = bx + a or y = bx - a? I wanted to make it look as clean as possible.

  lm_eqn = function(m) {

  l <- list(a = format(coef(m)[1], digits = 2),
      b = format(abs(coef(m)[2]), digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}

I have tried eliminated in the %.% and that throws up an error and I have tried inverting the order, but am having issues with the syntax in the if/else section of the function. I also would like to make it where the equation is formatted such that the coeff (a) is presented without the negative sign. abs(a) returns |a|. Thanks for any input! It is appreciated!

This follows from another thread( Adding Regression Line Equation and R2 on graph)

Community
  • 1
  • 1
Jeff
  • 105
  • 1
  • 8
  • Sorry, your last request didn't make much sense to me. – IRTFM Aug 16 '13 at 22:35
  • 1
    If you explain why you wanted to "eliminate the %.%" and whether you do or don't want to see the abs-bars in the output it would help understand you goals. – IRTFM Aug 16 '13 at 23:07

2 Answers2

1

If you want it in b*x+a form then just:

if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == 
                 b %.% italic(x) + a*","~~italic(r)^2~"="~r2, l)
  } else {
    eq <- substitute(italic(y) == 
               - b %.% italic(x) + a *"," ~~ italic(r)^2 ~"="~r2, l)  
  }

Writing R expressions requires understanding that there is a syntax rule: token/separator/token, but you can use either "+" or "-" as a unary separator. The upper portion of the plotmath symbol table in ?plotmath has the acceptable separators. Spaces and linefeeds get ignored.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

What error are you seeing? This works for me to give bx ± a as requested. You have to move the abs() to the definition of a instead of b and test coef(m)[1] instead of 2...

lm_eqn = function(m) {

  l <- list(a = format(abs(coef(m)[1]), digits = 2),
      b = format(coef(m)[2], digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[1] >= 0)  {
    eq <- substitute(italic(y) ==  b %.% italic(x) + a*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) ==  b %.% italic(x) - a*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}
beroe
  • 11,784
  • 5
  • 34
  • 79