在R中使用加权回归(lm)和引导包时出现问题

时间:2017-05-12 21:30:01

标签: r regression lm

我在使用启动函数将参数传递给统计信息(我有一个函数)时遇到问题。这是一个例子:

rm(list=ls())
library(faraway)
library(boot)
data(strongx)
g3 <- lm(crossx ~ energy, strongx, weights=rep(1, nrow(strongx)))

bootReg <- function(formulatostat, data, ind, weitostat) {
  weig <- weitostat[ind]
  fit <- lm(formula=formulatostat, data = data[ind, ], weights = weig)
  return(coef(fit))
}
wei <- rep(1, nrow(strongx))

bootResults <-
  boot(
    data = strongx,
    statistic = bootReg,
    R = 2000,
    formulatostat = crossx ~ energy,
    weitostat = wei)

eval(expr,envir,enclos)中的错误:找不到对象'weig'

当然,我的权重是1,所以加权部分是不必要的。但是在使用真实权重时问题仍然存在。这是我对其他数据的问题的演示。引导函数声明:“任何进一步的参数都可以通过...参数传递给统计信息。”貌似,formulatostat传递给bootReg而不是权重位。比较没有权重:

bootReg <- function(formulatostat, data, ind) {
  fit <- lm(formula=formulatostat, data = data[ind, ])
  return(coef(fit))
}
wei <- rep(1, nrow(strongx))

bootResults <-
  boot(
    data = strongx,
    statistic = bootReg,
    R = 2000,
    formulatostat = crossx ~ energy)

这很有效。任何关于如何合并重量的建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

似乎stats::model.frame函数(在lm函数中调用)正在查找给予weig参数的对象中名为data的对象,并且在定义公式(crossx ~ energy)的父环境中。

weig的data.frame中没有名为data的列。由于您已在crossx ~ energy函数之外定义了公式bootReg,因此lm函数无法找到weig对象。

您可以通过向赋予data参数的对象添加权重,或者在调用lm函数的同一环境中创建公式对象来修复错误。 / p>

解决方案1:

rm(list=ls())
library(faraway)
library(boot)
data(strongx)
g3 <- lm(crossx ~ energy, strongx, weights=rep(1, nrow(strongx)))

bootReg <- function(formulatostat, data, ind, weitostat) {
  input_to_lm <- data[ind, ]
  input_to_lm$weig <- weitostat[ind]
  fit <- lm(formula=formulatostat, data = input_to_lm, weights = weig)
  return(coef(fit))
}
wei <- rep(1, nrow(strongx))

bootResults <-
  boot(
    data = strongx,
    statistic = bootReg,
    R = 2000,
    formulatostat = crossx ~ energy,
    weitostat = wei)

解决方案2:

rm(list=ls())
library(faraway)
library(boot)
data(strongx)
g3 <- lm(crossx ~ energy, strongx, weights=rep(1, nrow(strongx)))

bootReg <- function(formulatostat, data, ind, weitostat) {
  weig <- weitostat[ind]
  fit <- lm(formula=as.formula(formulatostat), data = data[ind, ], weights = weig)
  return(coef(fit))
}
wei <- rep(1, nrow(strongx))

bootResults <-
  boot(
    data = strongx,
    statistic = bootReg,
    R = 2000,
    formulatostat = 'crossx ~ energy',
    weitostat = wei)