library(tidyverse)

met <- read_csv("https://denvirlab.marshall.edu/BMR617-2021/data/TH-B6-metabolic.csv") %>%
  separate(MouseID, sep="-", into=c("Strain","Diet","Id"))

met_summary <- met %>% group_by(Strain, Diet) %>% 
  summarise(Chol=mean(Cholesterol), CholSD = sd(Cholesterol), n=n(), sem=CholSD/sqrt(n))
met_summary

met_summary <- met_summary %>% mutate(criticalT = qt(0.975, df=n-1))
met_summary <- met_summary %>% mutate(MarginError = criticalT * sem) 
met_summary <- met_summary %>% mutate(ConfIntLower = Chol - MarginError) 
met_summary <- met_summary %>% mutate(ConfIntUpper = Chol + MarginError)

# Or you can do:
# met_summary <- met_summary %>% mutate(criticalT = qt(0.975, df=n-1)) %>%
#  met_summary %>% mutate(MarginError = criticalT * sem) %>%
#  met_summary %>% mutate(ConfIntLower = Chol - MarginError) %>%
#  met_summary %>% mutate(ConfIntUpper = Chol + MarginError)

# Or:
# met_summary <- met_summary %>% mutate(
#   criticalT = qt(0.975, df=n-1),
#   MarginError = criticalT * sem,
#   ConfIntLower = Chol - MarginError,
#   ConfIntUpper = Chol + MarginError
# )

met_summary %>% ggplot(aes(x=Strain, y=Chol, fill=Diet)) + 
  geom_bar(stat="identity", position = position_dodge()) +
  geom_errorbar(aes(ymin=ConfIntLower, ymax=ConfIntUpper), position = position_dodge(width=0.9), width=0.2)

# One useful thing you can do when working with graphs is to save them to a variable:

plt <- ggplot(met_summary, aes(x=Strain, y=Chol, fill=Diet)) # Just the axes
bar <- geom_bar(stat="identity", position = position_dodge())

plt + bar
errorCI <- geom_errorbar(aes(ymin=ConfIntLower, ymax=ConfIntUpper), position = position_dodge(width=0.9), width=0.2)

plt + bar + errorCI

# Now it's easy to experiment with different error bars, without redoing everything:

errorSEM <- geom_errorbar(aes(ymin=Chol - sem, ymax=Chol + sem), position = position_dodge(width=0.9), width=0.2)
errorSD <- geom_errorbar(aes(ymin=Chol - CholSD, ymax=Chol + CholSD), position = position_dodge(width=0.9), width=0.2)

plt + bar + errorSEM
plt + bar + errorSD
