【问题标题】:Bootstrap with Stepwise Regression in R在 R 中逐步回归的引导程序
【发布时间】:2020-08-03 14:55:43
【问题描述】:

我正在尝试获取引导样本并在 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)

}

【问题讨论】:

标签: r statistics regression statistics-bootstrap


【解决方案1】:

每次你做一个步骤时,系数的数量都是不同的,它与你的矩阵的维度不同,你不能“插入”它,你可以这样做:

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)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多