1

I am using the below function (found here) to generate linear model equations.

df <- data.frame(x = c(1:100))

df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)

lm_eqn <- function(df){
  m <- lm(y ~ x, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                   list(a = format(coef(m)[1], digits = 2), 
                        b = format(coef(m)[2], digits = 2), 
                        r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq));                 
}

lm_eqn(df)

[1] "italic(y) == \"14\" + \"3\" %.% italic(x) * \",\" ~ ~italic(r)^2 ~ \"=\" ~ \"0.806\""

However, this function was built for use in ggplot2, meaning it includes specific expression symbols that ggplot2 recognises and acts upon. I am using this function for something else. How can I alter the code so that I just end up with "y = 14 + 3x, r2=0.806"? Thank you.

J.Con
  • 4,101
  • 4
  • 36
  • 64

3 Answers3

2

If this is about dynamically generating/formatting an output string, you can also use stringr::str_interp:

# Sample data
set.seed(2017);
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)

# Fit
m <- lm(y ~ x, df);

# Extract coefficients and generate string
a <- coef(m)[1];
b <- coef(m)[2];
r2 <- summary(m)$r.squared;
stringr::str_interp("y = $[2.0f]{a} + $[2.0f]{b} x, R2 = $[4.3f]{r2}")
#[1] "y =  9 +  3 x, R2 = 0.793"

Or use sprintf:

sprintf("y = %2.0f + %2.0f x, R2 = %4.3f", a, b, r2);
#[1] "y =  9 +  3 x, R2 = 0.793"
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Good one. Might I ask what is the semi colon for in `m <- lm(y ~ x, df)`? – J.Con Apr 26 '18 at 04:07
  • @J.Con Ah, the semicolons are a force of habit; I tend to end my lines in R with `;`. They don't do any harm, but are not necessary (unless you have multiple commands in one line, which should be avoided anyway). If interested, see [here](https://stackoverflow.com/questions/28758225/whats-the-difference-in-using-a-semicolon-or-explicit-new-line-in-r-code) for more details. – Maurits Evers Apr 26 '18 at 04:10
  • Nice. Thank you. – J.Con Apr 26 '18 at 04:13
1

We can use glue

as.character(glue::glue("y = {round(a)} + {round(b)} x, R2 = {round(r2, 3)}"))
#[1] "y = 9 + 3 x, R2 = 0.793"

NOTE: Data based on @MauritsEvers post

akrun
  • 874,273
  • 37
  • 540
  • 662
0

Ah, found it.

g<-as.character("y = a + b x, R2= r2 ")

library(magrittr)

g %<>%
  gsub("a", format(coef(m)[1], digits = 2), .) %>%
  gsub("b", format(coef(m)[2], digits = 2), .) %>%
  gsub("r2", format(summary(m)$r.squared, digits = 3), .)

g

[1] "y = 14 + 3 x, R2= 0.806 "
J.Con
  • 4,101
  • 4
  • 36
  • 64