# Base-R version of the constructed Chapter 12 dispatch and join checks.
# Run from this directory: Rscript workbench.R
# Executed for editorial review in webR 0.6.1 (R/Wasm); see review/ch12-r-executed-output.txt.
d <- read.csv('dispatches.csv', stringsAsFactors = FALSE)
stopifnot(identical(names(d), c('Batch','Date','Region','Orders','Late')))
stopifnot(nrow(d) == 6L, length(unique(d$Batch)) == 6L)
stopifnot(all(d$Orders > 0L), all(d$Late >= 0L & d$Late <= d$Orders))
pooled <- sum(d$Late) / sum(d$Orders)
batch_mean <- mean(d$Late / d$Orders)
stopifnot(isTRUE(all.equal(pooled, .21)), isTRUE(all.equal(batch_mean, .15)))
regional <- aggregate(cbind(Orders,Late) ~ Region, data=d, FUN=sum)
regional <- regional[order(regional$Region),]
stopifnot(identical(as.integer(regional$Orders), c(45L,55L)))
stopifnot(identical(as.integer(regional$Late), c(8L,13L)))
cases <- data.frame(case_id=c('A','B','C','D'),resolved=c(1L,0L,1L,NA_integer_))
messages <- data.frame(message_id=c('A1','A2','A3','B1','C1','C2'),case_id=c('A','A','A','B','C','C'))
joined <- merge(cases,messages,by='case_id',all.x=TRUE,sort=TRUE)
stopifnot(nrow(joined)==7L, sum(is.na(joined$message_id))==1L)
counts <- aggregate(message_id ~ case_id,data=messages,FUN=length)
names(counts)[2] <- 'n_messages'
case_view <- merge(cases,counts,by='case_id',all.x=TRUE,sort=TRUE)
case_view$n_messages[is.na(case_view$n_messages)] <- 0L
stopifnot(nrow(case_view)==4L, identical(as.integer(case_view$n_messages),c(3L,1L,2L,0L)))
cat('DISPATCH ROWS',nrow(d),'UNIQUE BATCHES',length(unique(d$Batch)),'\n')
cat(sprintf('POOLED RATE %.2f%% BATCH MEAN %.2f%%\n',100*pooled,100*batch_mean))
print(regional,row.names=FALSE)
cat('RAW LEFT-JOIN ROWS',nrow(joined),'UNMATCHED CASES',sum(is.na(joined$message_id)),'\n')
cat('CASE-GRAIN ROWS',nrow(case_view),'KNOWN OUTCOMES',sum(!is.na(case_view$resolved)),'\n')
cat('BASE-R CHECKS PASS\n')
