0

I found a function that adds a regression line equation on graph. Adding Regression Line Equation and R2 on graph If I copy the function and data sample, everything works fine. But when I try to adapt the code, I get the message, that Y can't be found.

The Function:

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));                 
}

My data sample and adapted code:

library(tidyverse)
set.seed(1)
id <- 1:5000
zip <- sample(100:200, 5000, replace = TRUE)
outcome <- rbinom(5000, 1, 0.23)
df <- data.frame(id, outcome, zip) %>% as_tibble()
new_df <- df %>% group_by(zip) %>% summarise(ratio = mean(outcome))

library(ggplot2)
t <- ggplot(data = new_df, aes(x = zip, y = ratio)) +
  geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
  geom_point()

t1 <- t + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

Error in eval(predvars, data, env) : object 'y' not found

Where did I make the mistake? Thanks in advance!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Schillerlocke
  • 305
  • 1
  • 14
  • 2
    Your function has the line `m <- lm(y ~ x, df)` but there is no variable called `x` or `y` in your `df` variable. – MrFlick Nov 28 '18 at 21:04
  • I have edited the function and I don't get an error anymore but no equation on the graph. I have changed the variables names from the example so I understand which operator does what but clearly I can't the see right answer. And I'm fairly new to R and functions especially. – Schillerlocke Nov 28 '18 at 22:25
  • 1
    Well, you are plotting the label at zip=25 and ratio=300. those values are outside where all your points are. Maybe choose a different position. – MrFlick Nov 28 '18 at 22:27
  • Thank you, it works now and I understand a bit more. – Schillerlocke Nov 28 '18 at 22:45

0 Answers0