--- title: "STAT 516 Lec 09" format: html --- ```{r} ntr <- c(40.89,37.99,37.18,34.98,34.89,42.07, 41.22,49.42,45.85,50.15,41.99,46.69, 44.57,52.68,37.61,36.94,46.65,40.23, 41.90,39.20,43.29,40.45,42.91,39.97) block <- as.factor(c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4)) trt <- as.factor(c(2,5,4,1,6,3,1,3,4,6,5,2,6,3,5,1,2,4,2,4,6,5,3,1)) ``` ```{r} plot(ntr ~ trt) plot(ntr ~ block) ``` ANOVA table: ```{r} lm_out <- lm(ntr ~ trt + block) anova(lm_out) ``` Obtain REML estimators of the variance components: ```{r} library(lmerTest) lmer_out <- lmer(ntr ~ trt + (1|block)) summary(lmer_out) ``` Compare the first two treatments: ```{r} y1. <- mean(ntr[trt == "1"]) y2. <- mean(ntr[trt == "2"]) a <- 6 b <- 4 MSerror <- 2.68^2 alpha <- 0.05 tval <- qt(1- alpha/2,(a-1)*(b-1)) me <- tval * sqrt(MSerror) * sqrt(2/b) lo <- y1. - y2. - me up <- y1. - y2. + me c(lo,up) ``` How to get confidence intervals in the RCBD ```{r} ls_means(lmer_out) ``` Compare all pairs of means: ```{r} ls_means(lmer_out, pairwise= T) ``` If we want to do a Bonferroni adjustment for the fact that we are computing multiple CIs: ```{r} alpha <- 0.05/15 ls_means(lmer_out, pairwise = T,level = 1 - alpha) ``` What if we ignore the blocks and treat the data like a one-way ANOVA? ```{r} lm_oneway <- lm(ntr ~ trt) anova(lm_oneway) ``` Randomized block design with replication: ```{r} y <- c(104,114,109,124, 134,130,154,164, 146,142,152,156, 147,160,160,163, 133,146,156,161) nitr <- as.factor(c(0,0,0,0, 50,50,50,50, 100,100,100,100, 150,150,150,150, 200,200,200,200)) blk <- as.factor(c(1,1,2,2, 1,1,2,2, 1,1,2,2, 1,1,2,2, 1,1,2,2)) ``` ```{r} stripchart(y~nitr, vertical=T, method="jitter") ``` This ANOVA table will not have the correct main effect p-values: ```{r} lm_out <- lm(y ~ nitr + blk + nitr:blk) anova(lm_out) ``` Let's get the right F values and p values. ```{r} a <- nlevels(nitr) b <- nlevels(blk) n <- 2 y... <- predict(lm(y ~ 1)) # overall mean yi.. <- predict(lm(y ~ nitr)) # nitrogen leven means y.j. <- predict(lm(y ~ blk)) # block means yij. <- predict(lm(y ~ nitr + blk + nitr:blk)) # trt group means SST <- sum((y - y...)^2) SSA <- sum((yi.. - y...)^2) SSB <- sum((y.j. - y...)^2) SSE <- sum((y - yij.)^2) SSAB <- SST - (SSA + SSB + SSE) MSA <- SSA / (a - 1) MSB <- SSB / (b - 1) MSAB <- SSAB / ((a-1)*(b-1)) MSE <- SSE / (a*b*(n-1)) FA <- MSA / MSAB FB <- MSB / MSAB FAB <- MSAB / MSE pA <- 1 - pf(FA,a-1,(a-1)*(b-1)) pB <- 1 - pf(FB,b-1,(a-1)*(b-1)) FA FB ``` Method of moments estimators: ```{r} ``` Variance component estimates: ```{r} lmer_out <- lmer(y ~ nitr + (1|blk) + (1|nitr:blk) ) lmer_out ``` Confidence intervals for comparing all pairs of means: ```{r} ls_means(lmer_out,pairwise=T) ``` Adjust for multiple comparisons: ```{r} alpha <- 0.05/10 ls_means(lmer_out, pairwise = T, level = 1 - alpha) ```