# NOT RUN {
# example requires foreach
if (! require(foreach, quietly = TRUE))
stop("This example requires the \'foreach\' package")
# connect using defaults
createdb("rpgtesting")
connect("rpgtesting")
begin()
# write data frame contents
data(mtcars)
write_table(mtcars, row_names = "id", pkey = "id", overwrite = TRUE)
# expand rows to columns 8 rows at a time
x = foreach(i = cursor("SELECT * FROM mtcars", by = 8),
.combine = rbind) %do% { i$mpg }
print(x, digits = 2)
# parallel example
if (require(doParallel, quietly = TRUE))
{
# make the cluster
cl = makeCluster(2)
# must connect to database on each node
clusterEvalQ(cl, library(rpg))
clusterEvalQ(cl, connect("rpgtesting"))
clusterEvalQ(cl, begin())
# setup the dopar call
registerDoParallel(cl)
# take column averages 4 rows at a time
curs1 = cursor("SELECT * FROM mtcars", by = 4)
x = foreach(i = curs1, .combine = rbind, .inorder = FALSE) %dopar%
{
rr = paste0(range(abbreviate(i$id)), collapse = "-")
pid = get_conn_info("server.pid")
j = names(i) != "id"
mn = signif(apply(i[, j], 2, mean), 2)
c(rows = rr, backend = pid, mn)
}
x = as.data.frame(x)
row.names(x) = x$rows
x$rows = NULL
print(noquote(x))
clusterEvalQ(cl, rollback())
stopCluster(cl)
}
#cleanup
disconnect()
dropdb("rpgtesting")
# }
# NOT RUN {
# }
Run the code above in your browser using DataLab