I have a list object containing all my data and which is split into the different levels of my factor variable. Now I want to run a regression for every factor level and estimate the individual coefficients. Finally I want to weight the individual coefficients by the number of observations of each factor level. To get reasonable standard errors for this final coefficient estimation, I want to use the boot package in R. I tried to prepare a reproducible example for you.
This small data set contains 8 different factor levels. Suppose you want to regress y on x1 and x2 for every factor level and then value weight the coefficients.
bootdata <- split(bootdata, bootdata[2])
reboot <- function(d, f)
{
coefs <- matrix(NA,ncol=3,nrow=8)
nobs <- matrix(NA, ncol=1,nrow=8)
for(i in seq(1:8)){
data <- d[[i]]
workdata <- data[f,]
nobs[i] <- nrow(workdata)
fit <- lm(y~x1+x2, data=workdata)
for(j in seq(1:3)){
coefs[i,j] <- coef(fit)[j]
}
}
temp <- ((as.vector(nobs) * coefs)/sum(nobs))
coefs_result <- apply(temp, 2,function(x) sum(x))
retu(coefs_result)
}
boot_test <- boot(bootdata, reboot, R=10000)
I think I'm getting unreasonable coefficients and standard errors with this procedure and as far as I can see, the main problem is that the indices f refer to the whole data set and not to the individual list objects d[[i]]. I also tried to add the strata argument within boot() but that doesn't work for list objects. I would be very grateful for any suggested solution.
