Skip to content

Instantly share code, notes, and snippets.

@mikmart
Created November 20, 2019 08:43
Show Gist options
  • Save mikmart/250022c2410ff28291ce8ba74da52ebb to your computer and use it in GitHub Desktop.
Save mikmart/250022c2410ff28291ce8ba74da52ebb to your computer and use it in GitHub Desktop.
library(ggplot2)
library(patchwork)

set.seed(31987)

n <- 100
g <- sample(c("a", "b"), n, replace = TRUE)
x <- rexp(n, 1 / 5)
b <- c(5, 10)
y <- b[1] * log(x) + b[2] * (g == "a") + rnorm(n)

geom_lm <- function(...) {
  geom_smooth(method = "lm", se = FALSE, ...)
}
p <- qplot(x, y, colour = g) + geom_lm()
p + p + aes(x = log(x)) + plot_layout(guides = "collect")

summary(lm(y ~ x * g))
#> 
#> Call:
#> lm(formula = y ~ x * g)
#> 
#> Residuals:
#>      Min       1Q   Median       3Q      Max 
#> -12.9211  -1.1970   0.9806   2.4664   5.1550 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)   9.5530     0.7450  12.823   <2e-16 ***
#> x             1.0804     0.1014  10.653   <2e-16 ***
#> gb          -11.6882     1.1656 -10.028   <2e-16 ***
#> x:gb          0.4419     0.1825   2.421   0.0174 *  
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 3.738 on 96 degrees of freedom
#> Multiple R-squared:  0.8099, Adjusted R-squared:  0.804 
#> F-statistic: 136.3 on 3 and 96 DF,  p-value: < 2.2e-16
summary(lm(y ~ log(x) * g))
#> 
#> Call:
#> lm(formula = y ~ log(x) * g)
#> 
#> Residuals:
#>      Min       1Q   Median       3Q      Max 
#> -2.38847 -0.66242  0.02218  0.58159  2.54086 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)  9.87491    0.17507  56.406   <2e-16 ***
#> log(x)       4.98848    0.10375  48.082   <2e-16 ***
#> gb          -9.87115    0.25183 -39.197   <2e-16 ***
#> log(x):gb    0.04631    0.15103   0.307     0.76    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 0.9799 on 96 degrees of freedom
#> Multiple R-squared:  0.9869, Adjusted R-squared:  0.9865 
#> F-statistic:  2417 on 3 and 96 DF,  p-value: < 2.2e-16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment