# NOT RUN {
## these examples requires at least a dual core processor
## design-based simulation
data(eusilcP) #load data
# start cluster
cl <- makeCluster(2, type = "PSOCK")
# load package and data on workers
clusterEvalQ(cl, {
library(simFrame)
data(eusilcP)
})
# set up random number stream
clusterSetRNGStream(cl, iseed = "12345")
# control objects for sampling and contamination
sc <- SampleControl(size = 500, k = 50)
cc <- DARContControl(target = "eqIncome", epsilon = 0.02,
fun = function(x) x * 25)
# function for simulation runs
sim <- function(x) {
c(mean = mean(x$eqIncome), trimmed = mean(x$eqIncome, 0.02))
}
# export objects to workers
clusterExport(cl, c("sc", "cc", "sim"))
# run simulation on cluster
results <- clusterRunSimulation(cl, eusilcP,
sc, contControl = cc, fun = sim)
# stop cluster
stopCluster(cl)
# explore results
head(results)
aggregate(results)
tv <- mean(eusilcP$eqIncome) # true population mean
plot(results, true = tv)
## model-based simulation
# start cluster
cl <- makeCluster(2, type = "PSOCK")
# load package on workers
clusterEvalQ(cl, library(simFrame))
# set up random number stream
clusterSetRNGStream(cl, iseed = "12345")
# function for generating data
rgnorm <- function(n, means) {
group <- sample(1:2, n, replace=TRUE)
data.frame(group=group, value=rnorm(n) + means[group])
}
# control objects for data generation and contamination
means <- c(0, 0.25)
dc <- DataControl(size = 500, distribution = rgnorm,
dots = list(means = means))
cc <- DCARContControl(target = "value",
epsilon = 0.02, dots = list(mean = 15))
# function for simulation runs
sim <- function(x) {
c(mean = mean(x$value),
trimmed = mean(x$value, trim = 0.02),
median = median(x$value))
}
# export objects to workers
clusterExport(cl, c("rgnorm", "means", "dc", "cc", "sim"))
# run simulation on cluster
results <- clusterRunSimulation(cl, dc, nrep = 100,
contControl = cc, design = "group", fun = sim)
# stop cluster
stopCluster(cl)
# explore results
head(results)
aggregate(results)
plot(results, true = means)
# }
Run the code above in your browser using DataLab