如何避免MatchIt完全匹配过程中的错误?

时间:2017-10-07 10:54:18

标签: r matching

使用MatchIt包我想执行完全匹配过程。这样做我就会收到错误,即使vignette(第6页)声称:

  

没有其他选项可供完全匹配。

这是一个例子:

library(car)
WeightLoss1 <- WeightLoss
WeightLoss1$group <- as.integer(ifelse(WeightLoss1$group == "Control", 0, 1))

library(MatchIt)
matchit(group ~ wl1 + wl2 + wl3 + se1 + se2 + se3, method = "exact", data = WeightLoss1)

错误讯息:

Error in weights.subclass(psclass, treat) : No units were matched

错误?特征?误?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

@MarcoSandri 在评论中指出,没有匹配项。

我们可以通过检查功能确认这一点。

chkMtch <- function(d, grp.var) {
  spA <- lapply(split(d[, -grp.var], d[[grp.var]]), as.matrix)
  spB <- lapply(spA, function(x) split(x, row(x)))
  m <- t(outer(spB[[1]], spB[[2]], Vectorize(function(x, y) 
    all(identical(x, y)))))
  out <- spB[[1]][which(apply(m, 1, all))]
  return(if (length(out) == 0) message("no exact matches found" ) else out)
}

使用问题matchit的示例产生:

library(MatchIt)
fml <- group ~ wl1 + wl2 + wl3 + se1 + se2 + se3
matchit(fml, method="exact", data=WeightLoss)
# Error in weights.subclass(psclass, treat) : No units were matched

并使用我们的功能进行检查:

chkMtch(WeightLoss[all.vars(fml)], grp.var=1)
# no exact matches found

让我们举一个小例子来说明这一点,即创建具有明显完全不同的组的数据。

(d1 <- data.frame(matrix(c(rep(1, 12), rep(2, 16)), ncol=4, byrow=TRUE, 
                       dimnames=list(NULL, c("y", paste0("x", 1:3)))),
                group=factor(rep(0:1, c(3, 4)))))
#   y x1 x2 x3 group
# 1 1  1  1  1     0
# 2 1  1  1  1     0
# 3 1  1  1  1     0
# 4 2  2  2  2     1
# 5 2  2  2  2     1
# 6 2  2  2  2     1
# 7 2  2  2  2     1

matchit(group ~ y + x1 + x2 + x3, method="exact", data=d1)
# Error in weights.subclass(psclass, treat) : No units were matched

chkMtch(d1, grp.var=5)
# no exact matches found

如果我们现在有意将第二组的一行与第一组进行匹配,

(d2 <- as.data.frame(t(replace(t(d1), 21:25, 1))))
  y x1 x2 x3 group
1 1  1  1  1     0
2 1  1  1  1     0
3 1  1  1  1     0
4 2  2  2  2     1
5 1  1  1  1     1  # match
6 2  2  2  2     1
7 2  2  2  2     1

我们得到:

matchit(group ~ y + x1 + x2 + x3, method="exact", data=d2)
# Call: 
#   matchit(formula = group ~ y + x1 + x2 + x3, data = d2, method = "exact")
# 
# Exact Subclasses: 1
# 
# Sample sizes:
#           Control Treated
# All             3       4
# Matched         3       1
# Unmatched       0       3

chkMtch(d2, grp.var=5)

# $`2`
# [1] 1 1 1 1

数据

data("WeightLoss", package="carData")
WeightLoss$group <- ifelse(WeightLoss$group == "Control", 0, 1)