#!/usr/bin/env Rscript

# Run in the directory containing sleep.csv: Rscript check.R
observations <- read.csv("sleep.csv")
stopifnot(identical(names(observations), c("id", "method_1", "method_2")),
          nrow(observations) == 10L, !anyDuplicated(observations$id),
          all(complete.cases(observations)))

original <- datasets::sleep
for (group in c(1, 2)) {
  portion <- original[original$group == group, ]
  expected <- portion$extra[match(as.character(observations$id), portion$ID)]
  stopifnot(isTRUE(all.equal(observations[[paste0("method_", group)]], expected)))
}

paired <- t.test(observations$method_2, observations$method_1, paired = TRUE)
independent <- t.test(observations$method_2, observations$method_1)
print(data.frame(
  analysis = c("paired", "ignores_pairs"),
  difference_hours = mean(observations$method_2 - observations$method_1),
  lower_95 = c(paired$conf.int[1], independent$conf.int[1]),
  upper_95 = c(paired$conf.int[2], independent$conf.int[2]),
  p_value = c(paired$p.value, independent$p.value)
), digits = 5, row.names = FALSE)
