library(tidyverse) met <- read_csv("https://denvirlab.marshall.edu/BMR617-2021/data/TH-B6-metabolic.csv") met <- separate(met, MouseID, sep="-", into=c("Strain", "Diet", "ID")) # Filter for TH Chow: th_chow <- filter(met, Strain=="TH" & Diet == "Chow") # Get the cholesterol values from the table: chol_th_chow <- pull(th_chow, Cholesterol) m <- mean(chol_th_chow) s <- sd(chol_th_chow) n <- length(chol_th_chow) conf_level <- 0.95 t_star <- qt((1+conf_level)/2, df=n-1) conf_int_lower <- m - t_star*s/sqrt(n) conf_int_upper <- m + t_star*s/sqrt(n) conf_int <- function(x, conf_level=0.95) { m <- mean(x) s <- sd(x) n <- length(x) t_star <- qt((1+conf_level)/2, df=n-1) conf_int_lower <- m - t_star*s/sqrt(n) conf_int_upper <- m + t_star*s/sqrt(n) return(c(conf_int_lower, conf_int_upper)) } conf_int(chol_th_chow) met_grouped <- group_by(met, Strain, Diet) met_summary <- summarize(met_grouped, MeanCholesterol = mean(Cholesterol), lowerCI = conf_int(Cholesterol, conf_level=0.95)[[1]], upperCI = conf_int(Cholesterol, conf_level=0.95)[[2]]) barplot <- ggplot(met_summary, aes(x=Diet, y=MeanCholesterol, fill=Strain)) + geom_bar(stat='identity', position=position_dodge()) ciError <- geom_errorbar(aes(ymin=lowerCI, ymax=upperCI), position=position_dodge(width=0.9), width=0.2) barplot + ciError