【问题标题】:R matching dataframe before and after regression with missing values and subset regressionR在回归前后匹配数据框,缺失值和子集回归
【发布时间】:2013-07-11 22:51:35
【问题描述】:

我已经包含了一个玩具示例来重现我的错误:

data(cars)
cars$dist[cars$dist<5]<-NA
cars$fast<- (cars$speed>10)*1

fit<-lm(speed~dist,cars)


cl   <- function(dat,fm, cluster){
  require(sandwich, quietly = TRUE)
  require(lmtest, quietly = TRUE)
  M <- length(unique(cluster))
  N <- length(cluster)
  K <- fm$rank
  dfc <- (M/(M-1))*((N-1)/(N-K))
  uj  <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum));
  vcovCL <- dfc*sandwich(fm, meat=crossprod(uj)/N)
  result<-coeftest(fm, vcovCL)
  return(result)}

cl(cars,fit,cars$fast)

Error in tapply(x, cluster, sum) : arguments must have same length

问题在于原始数据帧大于回归中使用的数据帧,因为移除了 NA 和子集回归。我需要计算稳健的标准误差,因此我必须使用函数 cl 计算 SE,但是如何识别已删除的 NA 和适当的子集,以便我可以识别与数据帧一起使用的正确集群。

提前致谢。

【问题讨论】:

  • 请问为什么cl 函数没有引用“dat”在参数列表中?
  • 你是对的,我应该删除它。因为 cluster 是一个向量,应该与回归中使用的数据框匹配。

标签: r regression


【解决方案1】:

您可以使用complete.cases 来识别数据中的 NA,但在这种情况下,最好使用 lm 对象中的信息来处理 NA(感谢 @Dwin 指出更好的方法访问此信息以及更一般地如何简化此答案)。

data(cars)
cars$dist
cars$dist[cars$dist < 5] <- NA
cars$fast<- (cars$speed > 10) * 1
which(!complete.cases(cars))
## [1] 1 3

fit <- lm(speed ~ dist, data = cars)
fit$na.action
## 1 3 
## 1 3 
## attr(,"class")
## [1] "omit"

因此,你的最终函数应该是这样的

cl   <- function(fm, cluster){
    require(sandwich, quietly = TRUE)
    require(lmtest, quietly = TRUE)
    M <- length(unique(cluster))
    N <- length(cluster)
    K <- fm$rank
    dfc <- (M/(M-1))*((N-1)/(N-K))
    uj  <- apply(estfun(fm),2, function(x) tapply(x, cluster[-fm$na.action], sum));
    vcovCL <- dfc*sandwich(fm, meat=crossprod(uj)/N)
    result<-coeftest(fm, vcovCL)
    result}

cl(fit,cars$fast)
## t test of coefficients:

##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)   8.8424     2.9371    3.01  0.00422
## dist          0.1561     0.0426    3.67  0.00063

【讨论】:

  • 您可以使用cluster[complete.cases(dat)] 而不是“双重否定”,但我更喜欢使用cluster[-fit$na.action] 向量。
  • 首先,感谢您的帮助!我意识到我在我的问题中犯了一个错误。我猜缺失(NA)并不是回归中数据框较小的唯一来源。我的一些回归是子集回归。所以我提出的解决方案是使用相同的子集参数对原始数据框进行子集化,然后执行回归?有没有更优雅的方法来做到这一点?
猜你喜欢
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 2020-12-23
  • 1970-01-01
  • 2020-04-21
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多