0
votes

As per ex18q1 in "R for Data Science" I am trying to find the best model for the data:

sim1a <- tibble(
  x = rep(1:10, each = 3),
  y = x * 1.5 + 6 + rt(length(x), df = 2)
)

I've applied linear model and am trying to plot the results on a graph using ggplot:

sim1a_mod <- lm(x ~ y, data = sim1a)

ggplot(sim1a, aes(x, y)) +
  geom_point(size = 2, colour= "gray") +
  geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red")

coef(sim1a_mod)[[1]] prints -1.14403

coef(sim1a_mod)[[2]] prints 0.4384473

I create the plot with the data points, but the model is not showing. What am I doing wrong?

1
You can cheat and just use + geom_smooth(method = "lm") instead of geom_ablinePhil
@Phil Thanks, I noticed that when googling, and that's a great solution. For my comprehension though, and considering I'm pretty new to r I'd like to understand where my mistake is, and why this is not workingPreston
The issue was with your model. Try it with sim1a_mod <- lm(y ~ x, data = sim1a)Phil
@Phil I see... Thanks for that. Credit where credit's due if you put that in an answer you get the pointsPreston

1 Answers

3
votes

The nomenclature for typing formulas for model functions like lm(), glm(), lmer() etc. in R is always DV ~ IV1 + IV2 + ... + IVn where DV is your dependent variable and IVn is your list of independent variables. We typically chart the dependent variable on the y-axis and the independent variable on the x-axis, so in your case you'll need to change your sim1a_mod model to lm(y ~ x, data = sim1a).

In your original code, because you were running a different model, your line was being charted, but it was outside of your view. If you attempt to chart again with your original model with the following code you will then see your regression line:

ggplot(sim1a, aes(x, y)) +
geom_point(size = 2, colour= "gray") +
geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red") + 
scale_x_continuous(limits = c(-30, 30)) + scale_y_continuous(limits = c(-30, 30))

enter image description here