Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strengejacke/adc5e0494d8aa687f5921409a408285c to your computer and use it in GitHub Desktop.
Save strengejacke/adc5e0494d8aa687f5921409a408285c to your computer and use it in GitHub Desktop.
Explained variance for models with and without intercept
library(parameters)
library(performance)
library(ggplot2)
set.seed(123)
x <- 3 + rnorm(200)
y <- 4 + .5 * x + rnorm(100)
dat <- data.frame(x, y)
ggplot(dat, aes(x, y)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE, color = "green") +
stat_smooth(formula = y ~ 0 + x, method = "lm", se = FALSE, color = "red")
m1 <- lm(y ~ x, data = dat)
m2 <- lm(y ~ 0 + x, data = dat)
model_parameters(m1)
model_parameters(m2)
compare_performance(m1, m2, rank = TRUE)
@strengejacke
Copy link
Author

library(parameters)
library(performance)
library(ggplot2)

set.seed(123)
x <- 3 + rnorm(200)
y <- 4 + .5 * x + rnorm(100)
dat <- data.frame(x, y)

ggplot(dat, aes(x, y)) + 
  geom_point() + 
  stat_smooth(method = "lm", se = FALSE, color = "green") +
  stat_smooth(formula = y ~ 0 + x, method = "lm", se = FALSE, color = "red")
#> `geom_smooth()` using formula 'y ~ x'

m1 <- lm(y ~ x, data = dat)
m2 <- lm(y ~ 0 + x, data = dat)

model_parameters(m1)
#> Parameter   | Coefficient |   SE |       95% CI |     t |  df |      p
#> ----------------------------------------------------------------------
#> (Intercept) |        4.26 | 0.22 | [3.82, 4.70] | 19.05 | 198 | < .001
#> x           |        0.45 | 0.07 | [0.31, 0.59] |  6.35 | 198 | < .001
model_parameters(m2)
#> Parameter | Coefficient |   SE |       95% CI |     t |  df |      p
#> --------------------------------------------------------------------
#> x         |        1.75 | 0.04 | [1.68, 1.82] | 48.69 | 199 | < .001

compare_performance(m1, m2, rank = TRUE)
#> # Comparison of Model Performance Indices
#> 
#> Model | Type |    AIC |    BIC |   R2 | R2_adjusted | RMSE | BF | Performance_Score
#> -----------------------------------------------------------------------------------
#> m1    |   lm | 550.56 | 560.46 | 0.17 |        0.16 | 0.94 |  1 |            66.67%
#> m2    |   lm | 756.85 | 763.45 | 0.92 |        0.92 | 1.59 |  0 |            33.33%
#> 
#> Model m1 (of class lm) performed best with an overall performance score of 66.67%.

Created on 2020-08-06 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment