Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Last active May 22, 2017 10:32
Show Gist options
  • Save padpadpadpad/8c17875a37a33b2488058f18dab1b60e to your computer and use it in GitHub Desktop.
Save padpadpadpad/8c17875a37a33b2488058f18dab1b60e to your computer and use it in GitHub Desktop.
Testing a slope (or any other coefficient) of a linear model to a given value using bootstrapping
# test slope against defined value other than 0
# load packages
library(car)
library(ggplot2)
library(dplyr)
# create made up data
# set up gradient (grad) intercept (intercept) and standard deviation (sigma)
intercept = 10
grad = 1.2
sigma = 10
# create x and y
x <- 1:100
y <- intercept + grad*x + rnorm(x, 0, sigma)
d <- data.frame(x = x, y = y)
# model
mod <- lm(y ~ x, d)
confint(mod)
# fit the model 10000 times and extract the slope each time
slopes <- bootCase(mod, function(x) coef(x)[2], B = 10000)
slopes <- data.frame(x = slopes)
# this gives a vector of the slopes of 1000 fits
ggplot(slopes) +
geom_density(aes(x))
# get a p value for change of gradient being different a given number
# this is calculated as the number of times the slope is less or greater than a the number / number of total slopes - not an exact test!!!
# 1. different from 1.15
sum(slopes$x < 1.15)/nrow(slopes)
# can use smatr package (need to install if necessary) to do this with F tests using the smatr package
unlist(smatr::slope.test(d$y, d$x, test.value = 1.15, method = 'OLS'))
# significance will be based on the initial simulated data
# 2. different from 1.05
sum(slopes$x < 1.05)/nrow(slopes)
unlist(smatr::slope.test(d$y, d$x, test.value = 1.05, method = 'OLS'))
# plot
ggplot(slopes) +
geom_density(aes(x), fill = 'red', alpha = 0.5) +
geom_vline(aes(xintercept = 1.15)) +
geom_vline(aes(xintercept = 1.05)) +
theme_bw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment