# Create a parallel socket cluster
cl <- makeCluster(8) # use 8 workers
registerDoParallel(cl) # register the parallel backend
# Fit trees in parallel and compute predictions on the test set
predictions <- foreach(
icount(160),
.packages = "rpart",
.combine = cbind
) %dopar% {
# bootstrap copy of training data
index <- sample(nrow(ames_train), replace = TRUE)
ames_train_boot <- ames_train[index, ]
# fit tree to bootstrap copy
bagged_tree <- rpart(
Sale_Price ~ .,
control = rpart.control(minsplit = 2, cp = 0),
data = ames_train_boot
)
predict(bagged_tree, newdata = ames_test)
}
# Shutdown parallel cluster
stopCluster(cl)
predictions[1:5, 1:7]