1

让我们从上一个问题中做一个简单的练习。

在 R 中输入以下代码,我们最终将P1变量输出为:

library(Matching)
data(lalonde)
lalonde$ID <- 1:length(lalonde$age)
n <- 10
P1 <- rep(NA, n)

for (i in 1:n) {
  lalonde <- lalonde[sample(1:nrow(lalonde)), ]  # randomise the order
  X <- cbind(lalonde$age, lalonde$educ, lalonde$black, lalonde$hisp, 
            lalonde$married, lalonde$nodegr, lalonde$u74, lalonde$u75, 
            lalonde$re75, lalonde$re74)
  BalanceMat <- cbind(lalonde$age, lalonde$educ, lalonde$black, 
                      lalonde$hisp, lalonde$married, lalonde$nodegr, 
                      lalonde$u74, lalonde$u75, lalonde$re75, lalonde$re74, 
                      I(lalonde$re74*lalonde$re75))
  genout <- GenMatch(Tr=lalonde$treat, X=X, BalanceMatrix=BalanceMat, estimand="ATE", 
                     pop.size=16, max.generations=10, wait.generations=1)
  mout <- Match(Y=NULL, Tr=lalonde$treat, X=X,
                Weight.matrix=genout,
                replace=TRUE, ties=FALSE)
  summary(mout)
  treated <- lalonde[mout$index.treated, ]
  treated$Pair_ID <- treated$ID
  non.treated <- lalonde[mout$index.control, ]
  non.treated$Pair_ID <- treated$ID
  matched.data <- rbind(treated, non.treated)
  matched.data <- matched.data[order(matched.data$Pair_ID), ]
  P1[i] <- matched.data$ID[matched.data$Pair_ID == 1 & matched.data$treat == 0]
}

我们可以得到我们的结果:

summary(as.factor(P1))

我注意到这是 CPU 的低百分比,所以我调用doParallelpackage 并尝试运行loop并希望输出相同的结果(即 save P1[i])。但我收到一个错误:

require(doParallel)
cl <- makeCluster(3)
registerDoParallel(cl)

m <- 10
P1 <- rep(NA, m)

Result <- foreach(i=icount(m),.combine=cbind) %dopar% {
  lalonde <- lalonde[sample(1:nrow(lalonde)), ] # randomise the order
  X <- cbind(lalonde$age, lalonde$educ, lalonde$black, lalonde$hisp, 
            lalonde$married, lalonde$nodegr, lalonde$u74, lalonde$u75, 
            lalonde$re75, lalonde$re74)
  BalanceMat <- cbind(lalonde$age, lalonde$educ, lalonde$black, 
                      lalonde$hisp, lalonde$married, lalonde$nodegr, 
                      lalonde$u74, lalonde$u75, lalonde$re75, lalonde$re74, 
                      I(lalonde$re74*lalonde$re75))
  genout <- GenMatch(Tr=lalonde$treat, X=X, BalanceMatrix=BalanceMat, estimand="ATE", 
                     pop.size=16, max.generations=10, wait.generations=1)
  mout <- Match(Y=NULL, Tr=lalonde$treat, X=X,
                Weight.matrix=genout,
                replace=TRUE, ties=FALSE)
  summary(mout)
  treated <- lalonde[mout$index.treated, ]
  treated$Pair_ID <- treated$ID
  non.treated <- lalonde[mout$index.control, ]
  non.treated$Pair_ID <- treated$ID
  matched.data <- rbind(treated, non.treated)
  matched.data <- matched.data[order(matched.data$Pair_ID), ]
  P1[i] <- matched.data$ID[matched.data$Pair_ID == 1 & matched.data$treat == 0 ]
}

GenMatch是找不到的。有什么建议可以改进我的代码吗?

4

1 回答 1

1

创建集群时,您会创建新的不可见 R 会话。因此,您必须为集群提供非基本功能。尝试运行:

clusterEvalQ(cl,library(Matching))
clusterEvalQ(cl,library(rgenoud))
于 2015-06-22T13:41:37.590 回答