Bootstrapping using R to obtain differences in means adjusted for covariate differences

In this example activity differences in word groups (diffy) are adjusted for activity differences in suffix endings in these words (diffx). 100 bootstrap samples are drawn with replacement and the word group activity difference which is not due to the suffix difference in the words computed. Finally a t-test is performed over the 100 sample adjusted mean word difference activities.

diffy <- c(-1,-2,0,1,2,3,2.1)
diffx <- c(-3,4,2,5,1.2,3,2)

nsamp <- 100

b <- rep(0,nsamp)

for (j in 1:nsamp) {
x <- 1:length(diffy)

y <- sample(x, size=length(diffy), replace=T)

yreg <- diffy[y]
xreg <- diffx[y]

out <- glm(yreg ~ xreg)

b[j] <- mean(yreg) - out$coefficients[2]*mean(xreg)
}

* one sample t-test

mn <- mean(b)
se <- sqrt(var(b)/nsamp)
tout <- mn/se
pval <- 2*pt(-abs(mn/se), nsamp-1)

You can then compute a 95% CI but make sure the number of bootstrap samples, nsamp, is a multiple of 20.

bs <- sort(b)
ind <- trunc(0.05*nsamp)
bs[ind]
ind <- trunc(0.95*nsamp)
bs[ind]