# Single-dose cell viability as percent of vehicle control: wells or independent experiments as n, percent scale or
# log ratio. R 4.3.3, base R.
d <- read.csv("viability.csv")                       # one row per well: experiment, condition (blank/vehicle/treated), well, absorbance
f2 <- function(p) formatC(signif(p, 2), format = "g")
blank <- tapply(d$absorbance[d$condition == "blank"], d$experiment[d$condition == "blank"], mean)
d$signal <- d$absorbance - blank[d$experiment]       # blank-subtracted
w <- d[d$condition != "blank", ]
veh <- tapply(w$signal[w$condition == "vehicle"], w$experiment[w$condition == "vehicle"], mean)
trt <- tapply(w$signal[w$condition == "treated"], w$experiment[w$condition == "treated"], mean)
w$pct <- 100 * w$signal / veh[w$experiment]          # percent of the same experiment's mean vehicle signal
for (e in names(veh)) cat(sprintf("%s: vehicle signal %.3f, treated %.3f, treated %.1f%% of vehicle\n", e, veh[[e]], trt[[e]], 100 * trt[[e]] / veh[[e]]))
tw <- w$pct[w$condition == "treated"]; vw <- w$pct[w$condition == "vehicle"]
a <- t.test(tw, mu = 100)
cat(sprintf("A. Wells as n (%d treated wells), one-sample t-test against 100%%: mean %.1f%%, p = %s\n", length(tw), mean(tw), f2(a$p.value)))
b <- t.test(tw, vw)
cat(sprintf("B. Wells as n (%d vs %d), Welch t-test on percent of vehicle: difference %.1f points, p = %s\n", length(tw), length(vw), mean(tw) - mean(vw), f2(b$p.value)))
pe <- 100 * trt / veh; c1 <- t.test(pe, mu = 100)
cat(sprintf("C. Experiments as n (%d), one-sample t-test of percent of vehicle against 100%%: mean %.1f%% (95%% CI %.1f to %.1f), p = %s\n", length(pe), mean(pe), c1$conf.int[1], c1$conf.int[2], f2(c1$p.value)))
stopifnot(all(trt > 0), all(veh > 0))                # a blank-subtracted mean of 0 or below cannot be logged
lr <- log(trt / veh); t1 <- t.test(lr)
cat(sprintf("D. Experiments as n (%d), one-sample t-test of log(treated / vehicle): ratio %.3f (95%% CI %.3f to %.3f), p = %s\n", length(lr), exp(mean(lr)), exp(t1$conf.int[1]), exp(t1$conf.int[2]), f2(t1$p.value)))
p <- t.test(trt, veh, paired = TRUE)
cat(sprintf("E. Experiments as n (%d), paired t-test on blank-subtracted signal: difference %.3f, p = %s\n", length(trt), mean(trt - veh), f2(p$p.value)))
