[英]Bootstrap with Stepwise Regression in R
我正在嘗試在 R 中獲取引導樣本並進行逐步回歸。 我正在嘗試查看回歸系數的分布,但我正在處理的“bhat”矩陣主要是打印出 NA,但第一行除外(所有列的數字相同)。 我怎樣才能解決這個問題?
B <- 100 #number of bootstrap samples
n <- nrow(dat)
d <- ncol(dat) - 1
bhat <- matrix(NA, nrow = B, ncol = ncol(dat) - 1)
for(b in 1:B) {
s <- sample(1:n, n, replace=TRUE)
samp <- as.matrix(dat[s, c(1:15)])
samp <- as.data.frame(samp)
#stepwise regression
null <- lm(dat$Y ~ 1, data=samp)
full <- lm(dat$Y ~ ., data=samp)
fit <- step(null, scope=formula(full), direction="forward", k=log(n), trace=0)
bhat[b,] <- coef(fit)
}
每次你做一個步驟時,系數的數量都是不同的,它與你的矩陣的維度不同,你不能“插入”它,你可以這樣做:
dat = data.frame(Y=rnorm(100),matrix(rnorm(100*15),ncol=15))
colnames(dat)[-1] = paste0("Var",1:15)
B <- 100 #number of bootstrap samples
n <- nrow(dat)
d <- ncol(dat) - 1
full_mdl = colnames(model.matrix(Y~.,data=dat))
bhat <- matrix(NA, nrow = B, ncol = length(full_mdl))
colnames(bhat) = full_mdl
for(b in 1:B) {
samp <- dat[sample(1:n, n, replace=TRUE), c(1:15)]
null <- lm(dat$Y ~ 1, data=samp)
full <- lm(dat$Y ~ ., data=samp)
fit <- step(null, scope=formula(full), direction="forward", k=log(n), trace=0)
bhat[b,names(coef(fit))] <- coef(fit)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.