# WP5 Simulation
# Version 14
# Figures for the Preliminary Analysis with Sandbox Data 

library(ggplot2)
library(dplyr)
library(tidyr)
library(here)

here::i_am("Analysis_animals.R")

animals_out <- read.csv2("animals_out.csv"
                         ,sep=",",
                         header = FALSE,
                         stringsAsFactors=FALSE,
                         numerals = "allow.loss")

##############################################################################

custom_palette<- c("#000000",# t-test
                   
                   "#DDBB00",# rule of 10
                   "#FF9922",# N=50
                   
                   "#A495ED",# p=005
                   "#6D28D9",# p=005 adj
                   
                   "#A48464",# power one 08
                   "#7C6053",# power one 09
                   
                   "#A1A1A1",# power meta 08
                   "#6B6B6B",# power meta 09
                   
                   "#1E3A8A",# mid s 08
                   "#83B5ED",# mid s 09
                   "#1B63E6",# mid m 08
                   "#4B93FF",# mid m 09
                   "#2C6A8A",# mid l 08
                   "#5C9AAA",# mid l 09
                   
                   "#448822",# rlm
                   "#76BA44",# rlm power 08
                   "#00AA77",# rlm power 09
                   
                   "#DC2626",# multi lab
                   "#CC88BB",# multi lab 08
                   "#F442B6" # multi lab 09 
)

interventions <- c("t test", "Rule of ten", "N=50", "p<005", 
                   "p<005 adj", "Power one 08", "Power one 09", "Power meta 08", 
                   "Power meta 09", "MID small 08", "MID small 09" , "MID medium 08", "MID medium 09" ,
                   "MID large 08", "MID large 09", "RLM", "RLM power 08", 
                   "RLM power 09", "Multi-lab (ML)", "ML power 08", "ML power 09")

##############################################################################

# Plotting Functions

# Function for the ranking graph

#-----------------------------------
rank_graph <- function(selected_data, y_label){
  
  # Compute rankings
  rankings <- apply(selected_data, 1, function(x) rank(rank(x)))
  
  rankings_df <- as.data.frame(rankings) %>%
    dplyr::mutate(DataSet = factor(1:21)) %>%
    tidyr::pivot_longer(-DataSet, names_to = "Variable", values_to = "Rank") %>%
    dplyr::mutate(Variable = as.numeric(gsub("V", "", Variable)))
  
  # Mean rank per intervention legend order
  mean_ranks <- rankings_df %>%
    dplyr::group_by(DataSet) %>%
    dplyr::summarise(mean_rank = mean(Rank), .groups = "drop")
  
  legend_order <- mean_ranks %>%
    dplyr::arrange(dplyr::desc(mean_rank)) %>%
    dplyr::pull(DataSet) %>%
    as.character()
  
  rankings_df <- rankings_df %>%
    dplyr::mutate(DataSet = factor(as.character(DataSet), levels = legend_order))
  
  # Colors
  # custom_palette <- c(RColorBrewer::brewer.pal(9, "Set1"),
  #                      RColorBrewer::brewer.pal(8, "Dark2"),
  #                     RColorBrewer::brewer.pal(4, "Set2"))
  #  custom_palette[6] <- "#DDDD11"
  
  pal_ordered    <- custom_palette[as.integer(legend_order)]
  labels_ordered <- interventions[as.integer(legend_order)]
  col_map <- stats::setNames(pal_ordered, legend_order)
  
  # --- t-test step-function (DataSet == "1") ---
  df_tt <- rankings_df %>%
    dplyr::filter(DataSet == "1") %>%
    dplyr::arrange(Variable)
  
  x_min  <- min(rankings_df$Variable)
  x_max  <- max(rankings_df$Variable)
  y_base <- min(rankings_df$Rank) - 0.5
  
  # Horizontal plateaus
  df_tt_h <- df_tt %>%
    dplyr::mutate(
      x0 = if_else(Variable == x_min, Variable, Variable - 0.5),
      x1 = if_else(Variable == x_max, Variable, Variable + 0.5)
    )
  
  # Vertical connectors (FIXED)
  df_tt_v <- df_tt %>%
    dplyr::mutate(
      xv = Variable + 0.5,
      y0 = Rank,
      y1 = dplyr::lead(Rank)
    ) %>%
    dplyr::filter(!is.na(y1))
  
  # Shaded area
  df_tt_rect <- df_tt_h %>%
    dplyr::transmute(
      xmin = x0, xmax = x1,
      ymin = y_base, ymax = Rank
    )
  
  ggplot2::ggplot(rankings_df, ggplot2::aes(x = Variable, y = Rank, group = DataSet, color = DataSet)) +
    ggplot2::coord_fixed(ratio = 0.6) +
    
    # Other interventions
    ggplot2::geom_line(
      data = subset(rankings_df, DataSet != "1"),
      alpha = 0.4
    ) +
    ggplot2::geom_point(
      data = subset(rankings_df, DataSet != "1"),
      size = 3
    ) +
    
    # t-test shaded step
    ggplot2::geom_rect(
      data = df_tt_rect,
      ggplot2::aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
      inherit.aes = FALSE,
      fill = "black",
      alpha = 0.10
    ) +
    ggplot2::geom_segment(
      data = df_tt_h,
      ggplot2::aes(x = x0, xend = x1, y = Rank, yend = Rank, color = DataSet),
      linewidth = 2.5
    ) +
    ggplot2::geom_segment(
      data = df_tt_v,
      ggplot2::aes(x = xv, xend = xv, y = y0, yend = y1, color = DataSet),
      linewidth = 0.8
    ) +
    
    ggplot2::geom_line(
      data = subset(rankings_df, DataSet != "1"),
      alpha = 0.4
    ) +
    ggplot2::geom_point(
      data = subset(rankings_df, DataSet != "1"),
      size = 3
    ) +
    
    ggplot2::scale_color_manual(
      values = col_map,
      breaks = legend_order,
      labels = labels_ordered
    ) +
    ggplot2::labs(
      x = "Animal Data Set",
      y = y_label,
      color = "Interventions"
    ) +
    ggplot2::theme_minimal() +
    ggplot2::theme(
      legend.position = "right",
      panel.grid.minor = ggplot2::element_blank()
    )
}


# Function for the line-graph by data set


line_graph <- function(selected_data, y_label,n_trials){
  
  plot_data <- as.data.frame(selected_data) %>%
    dplyr::mutate(Set = factor(1:28)) %>%
    tidyr::pivot_longer(-Set, names_to = "Variable", values_to = "Value") %>%
    dplyr::mutate(
      Variable = as.numeric(gsub("V", "", Variable)),
      Set_num  = as.numeric(as.character(Set)),
      Value    = as.numeric(Value),
      SE       = sqrt(Value * (1 - Value) / n_trials)
    )
  
  # ---- Compute mean per intervention → legend order ----
  mean_vals <- plot_data %>%
    dplyr::group_by(Variable) %>%
    dplyr::summarise(mean_value = mean(Value, na.rm = TRUE), .groups = "drop")
  
  legend_order <- mean_vals %>%
    dplyr::arrange(dplyr::desc(mean_value)) %>%
    dplyr::pull(Variable)
  
  # Make Variable an ordered factor everywhere
  plot_data <- plot_data %>%
    dplyr::mutate(
      Variable = factor(Variable, levels = legend_order)
    )
  
  # Split again after factoring
  df_tt    <- dplyr::filter(plot_data, Variable == "1") %>% dplyr::arrange(Set_num)
  df_other <- dplyr::filter(plot_data, Variable != "1")
  
  
  # Reorder palette + labels to match legend order
  pal_ordered    <- custom_palette[as.integer(legend_order)]
  labels_ordered <- interventions[as.integer(legend_order)]
  
  col_map <- stats::setNames(pal_ordered, as.character(legend_order))
  
  y_base <- -0.05
  
  ggplot2::ggplot() +
    ggplot2::coord_fixed(ratio = 10) +
    
    # --- others first ---
    ggplot2::geom_line(
      data = df_other,
      mapping = ggplot2::aes(x = Set, y = Value, group = Variable, color = Variable),
      alpha = 0.3
    ) +
    
    # --- t-test shading ---
    ggplot2::geom_ribbon(
      data = df_tt,
      mapping = ggplot2::aes(x = Set_num, ymin = y_base, ymax = Value),
      inherit.aes = FALSE,
      fill = "black",
      alpha = 0.1
    ) +
    
    ggplot2::geom_line(
      data = df_other,
      mapping = ggplot2::aes(x = Set, y = Value, group = Variable, color = Variable),
      alpha = 0.3
    ) +
    
    ggplot2::geom_point(
      data = df_other,
      mapping = ggplot2::aes(x = Set, y = Value, color = Variable),
      size = 3
    ) +
    ggplot2::geom_errorbar(
      data = df_other,
      mapping = ggplot2::aes(x = Set, ymin = Value - SE, ymax = Value + SE, color = Variable),
      width = 0.2,
      linewidth = 0.3
    ) +
    
    # --- t-test on top ---
    ggplot2::geom_line(
      data = df_tt,
      mapping = ggplot2::aes(x = Set, y = Value, group = Variable, color = Variable),
      linewidth = 0.4
    ) +
    ggplot2::geom_point(
      data = df_tt,
      mapping = ggplot2::aes(x = Set, y = Value, color = Variable),
      size = 3.5
    ) +
    ggplot2::geom_errorbar(
      data = df_tt,
      mapping = ggplot2::aes(x = Set, ymin = Value - SE, ymax = Value + SE, color = Variable),
      width = 0.2,
      linewidth = 0.4
    ) +
    
    
    
    ggplot2::scale_color_manual(
      values = col_map,
      breaks = as.character(legend_order),
      labels = labels_ordered
    ) +
    ggplot2::labs(
      x = "Animal Data Set",
      y = y_label,
      color = "Intervention"
    ) +
    ggplot2::scale_y_continuous(limits = c(-0.05, 1.05)) +
    ggplot2::theme_minimal() +
    ggplot2::theme(
      legend.position = "right",
      panel.grid.minor = ggplot2::element_blank()
    )
}


# Function for the dot-graph by intervention


dot_graph <-function(selected_data,y_label,n_trials){
  
  # Convert the data into a long-format data frame for ggplot2
  plot_data <- as.data.frame(selected_data) %>%
    mutate(DataSet = factor(1:28)) %>%  # Rows 1:14
    pivot_longer(-DataSet, names_to = "Variable", values_to = "Value") %>%
    mutate(
      Variable = gsub("V", "", Variable),  
      Value = as.numeric(Value),  # Ensure numeric values
      SE = sqrt(Value * (1 - Value) / n_trials) # SE for n Bernoulli trials
    )
  # Better color palette
  # custom_palette <- colorRampPalette(RColorBrewer::brewer.pal(12, "Set3"))(28)
  
  # Plot using ggplot2
  ggplot(plot_data, aes(x = Variable, y = Value, color = DataSet)) +
    coord_fixed(ratio=200) +
    geom_point(size=3) +
    geom_errorbar(aes(ymin = Value - SE, ymax = Value + SE), width = 0.2, linewidth = 0.3) +
    #scale_color_manual(values = custom_palette) + 
    scale_x_discrete(labels= interventions) +
    scale_y_continuous(
      limits = c(-0.001, 0.05)
    ) +
    labs(
      x = "Intervention",                            
      y = y_label,
      color = "Animal Data Set"
    ) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(angle = 60, hjust = 1), # Rotated x-axis labels
      legend.position = "right",
      panel.grid.minor = element_blank()
    )
}


# Percent increase function
median_percent_change <- function(x, y, na.rm = TRUE) {
  rel_change <- (y - x) / x * 100
  if(na.rm)
    rel_change <- rel_change[is.finite(rel_change)]
  median(rel_change)
}



##################################################

# Figures for Final Analysis

n_trials <- 100000

animals_meta <- read.csv2("animals_meta.csv",sep=","
                         ,header = FALSE)
animals_meta[] <- sapply(animals_meta, as.numeric)
names(animals_meta) <- c("study_id","estimate","lb_ci" ,"ub_ci","significant",
                        "se_estimate","i_squared","q_test","q_test_pval",
                        "tau_squared")

raw_data <- read.csv("Animal_Data.csv",sep=";",dec=".",fill=TRUE,
                     na.strings="NA",row.names = NULL,as.is=TRUE)

# adding n_of_studies to meta data
n_of_studies <- vector(length=28)
for(i in 1 : 28){n_of_studies[i] <- sum(raw_data[1]==animals_meta[i,1])}
animals_meta$n_of_studies <- n_of_studies


# Ranked by effect size  -------------------------------------------------------

ranked_by_es <- rank(abs(animals_meta$estimate) ,ties.method = "first")
animals_out_es <- animals_out[order(ranked_by_es), ]
row.names(animals_out_es) <- c(1:28)

# 1. True Positive Rate

input_data <- animals_out_es[, 1:21]
names(input_data) <- vars <- paste0("V", 1:21)

pdf(file="Animals True Positive Rate es.pdf", paper="a4r", width=11)
line_graph(input_data,"True Positive Rate",100000)
dev.off()

# 2. False Positive Rate

pdf(file="Animals False Positive Rate.pdf", paper="a4r", width=10)
dot_graph(animals_out[, 22:42],"False Positive Rate",100000)
dev.off()

# 3. PPV:

ppv_matrix <-apply(animals_out_es[, 1:21], 2, as.numeric) / 
  (apply(animals_out_es[, 1:21], 2, as.numeric) +
     apply(animals_out_es[, 22:42], 2, as.numeric))

pdf(file="Animals Rank PPV es.pdf", paper="a4r", width=11)
line_graph(ppv_matrix,"Positive Predictive Value",100000)
dev.off()

pdf(file="Animals Rank PPV es.pdf", paper="a4r", width=11)
rank_graph(ppv_matrix,"Rank by Positive Predictive Value")
dev.off()


toprank <-c()
for(i in 1:28){
  toprank <- c(toprank,
               order(ppv_matrix[i,])[21])
}
table(toprank)

topthree <-c()
for(i in 1:28){
  topthree <- c(topthree,
                order(ppv_matrix[i,])[19:21])
}
table(topthree)

rank_mat <-matrix(nrow = 28, ncol = 21)
for(i in 1:28){
  rank_mat[i,]<-22-rank(as.numeric(ppv_matrix[i,]))
}
colSums(rank_mat)/28

input_data <- ppv_matrix
animal_percent_increase <-c(
  median_percent_change(as.numeric(input_data[,2]),as.numeric(input_data[,3])),
  median_percent_change(as.numeric(input_data[,4]),as.numeric(input_data[,5])),
  median_percent_change(as.numeric(input_data[,16]),as.numeric(input_data[,17])),
  median_percent_change(as.numeric(input_data[,19]),as.numeric(input_data[,20])),
  median_percent_change(as.numeric(input_data[,6]),as.numeric(input_data[,7])),
  median_percent_change(as.numeric(input_data[,8]),as.numeric(input_data[,9])),
  median_percent_change(as.numeric(input_data[,17]),as.numeric(input_data[,18])),
  median_percent_change(as.numeric(input_data[,20]),as.numeric(input_data[,21]))
)
animal_percent_increase

# 4. Rejection Edgington's p-value

input_data <- animals_out_es[, 43:63]
names(input_data) <- vars <- paste0("V", 1:21)

n_trials <- 50000

pdf(file="Animals Edgintons p es.pdf", paper="a4r", width=11)
line_graph(input_data,"Edgington's p-value: Proportion sign.",50000)
dev.off()

pdf(file="Animals Rank Edgingtons p es.pdf", paper="a4r", width=11)
rank_graph(input_data,"Rank by Edgington's p-value")
dev.off()

toprank <-c()
for(i in 1:28){
  toprank <- c(toprank,
               order(as.numeric(input_data[i,]))[21])
}
table(toprank)

topthree <-c()
for(i in 1:28){
  topthree <- c(topthree,
                order(as.numeric(input_data[i,]))[19:21])
}
table(topthree)

rank_mat <-matrix(nrow = 28, ncol = 21)
for(i in 1:28){
  rank_mat[i,]<-22-rank(as.numeric(input_data[i,]))
}
colSums(rank_mat)/28

animal_percent_increase <-c(
  median_percent_change(as.numeric(input_data[,2]),as.numeric(input_data[,3])),
  median_percent_change(as.numeric(input_data[,4]),as.numeric(input_data[,5])),
  median_percent_change(as.numeric(input_data[,16]),as.numeric(input_data[,17])),
  median_percent_change(as.numeric(input_data[,19]),as.numeric(input_data[,20])),
  median_percent_change(as.numeric(input_data[,6]),as.numeric(input_data[,7])),
  median_percent_change(as.numeric(input_data[,8]),as.numeric(input_data[,9])),
  median_percent_change(as.numeric(input_data[,17]),as.numeric(input_data[,18])),
  median_percent_change(as.numeric(input_data[,20]),as.numeric(input_data[,21]))
)
animal_percent_increase


# 5. Two-trial success rule

input_data <- animals_out_es[, 127:147]
names(input_data) <- vars <- paste0("V", 1:21)

pdf(file="Animals Two Trial es.pdf", paper="a4r", width=11)
line_graph(input_data,"Two Trial Rule: Proportion sign.",50000)
dev.off()

pdf(file="Animals Rank Two Trial es.pdf", paper="a4r", width=11)
rank_graph(input_data,"Rank by Two Trial Rule")
dev.off()

toprank <-c()
for(i in 1:28){
  toprank <- c(toprank,
               order(as.numeric(input_data[i,]))[21])
}
table(toprank)

topthree <-c()
for(i in 1:28){
  topthree <- c(topthree,
                order(as.numeric(input_data[i,]))[19:21])
}
table(topthree)

rank_mat <-matrix(nrow = 28, ncol = 21)
for(i in 1:28){
  rank_mat[i,]<-22-rank(as.numeric(input_data[i,]))
}
colSums(rank_mat)/28

animal_percent_increase <-c(
  median_percent_change(as.numeric(input_data[,2]),as.numeric(input_data[,3])),
  median_percent_change(as.numeric(input_data[,4]),as.numeric(input_data[,5])),
  median_percent_change(as.numeric(input_data[,16]),as.numeric(input_data[,17])),
  median_percent_change(as.numeric(input_data[,19]),as.numeric(input_data[,20])),
  median_percent_change(as.numeric(input_data[,6]),as.numeric(input_data[,7])),
  median_percent_change(as.numeric(input_data[,8]),as.numeric(input_data[,9])),
  median_percent_change(as.numeric(input_data[,17]),as.numeric(input_data[,18])),
  median_percent_change(as.numeric(input_data[,20]),as.numeric(input_data[,21]))
)
animal_percent_increase


# 6. Consistency

input_data <- animals_out_es[, 85:105]
names(input_data) <- vars <- paste0("V", 1:21)
  
pdf(file="Animals Consistency es.pdf", paper="a4r", width=11)
line_graph(input_data,"Consistency",50000)
dev.off()

pdf(file="Animals Rank Consistency es.pdf", paper="a4r", width=11)
rank_graph(input_data,"Rank by Consistency")
dev.off()


toprank <-c()
for(i in 1:28){
  toprank <- c(toprank,
               order(as.numeric(input_data[i,]))[21])
}
table(toprank)

topthree <-c()
for(i in 1:28){
  topthree <- c(topthree,
                order(as.numeric(input_data[i,]))[19:21])
}
table(topthree)

rank_mat <-matrix(nrow = 28, ncol = 21)
for(i in 1:28){
  rank_mat[i,]<-22-rank(as.numeric(input_data[i,]))
}
colSums(rank_mat)/28

animal_percent_increase <-c(
  median_percent_change(as.numeric(input_data[,2]),as.numeric(input_data[,3])),
  median_percent_change(as.numeric(input_data[,4]),as.numeric(input_data[,5])),
  median_percent_change(as.numeric(input_data[,16]),as.numeric(input_data[,17])),
  median_percent_change(as.numeric(input_data[,19]),as.numeric(input_data[,20])),
  median_percent_change(as.numeric(input_data[,6]),as.numeric(input_data[,7])),
  median_percent_change(as.numeric(input_data[,8]),as.numeric(input_data[,9])),
  median_percent_change(as.numeric(input_data[,17]),as.numeric(input_data[,18])),
  median_percent_change(as.numeric(input_data[,20]),as.numeric(input_data[,21]))
)
animal_percent_increase


# 7. Coverage

input_data <- animals_out_es[, 211:231]
names(input_data) <- vars <- paste0("V", 1:21)

pdf(file="Animals Coverage es.pdf", paper="a4r", width=11)
line_graph(input_data,"Coverage",100000)
dev.off()

pdf(file="Animals Rank Coverage es.pdf", paper="a4r", width=11)
rank_graph(input_data,"Rank by Coverage")
dev.off()

toprank <-c()
for(i in 1:28){
  toprank <- c(toprank,
               order(as.numeric(input_data[i,]))[21])
}
table(toprank)

topthree <-c()
for(i in 1:28){
  topthree <- c(topthree,
                order(as.numeric(input_data[i,]))[19:21])
}
table(topthree)

rank_mat <-matrix(nrow = 28, ncol = 21)
for(i in 1:28){
  rank_mat[i,]<-22-rank(as.numeric(input_data[i,]))
}
colSums(rank_mat)/28

animal_percent_increase <-c(
  median_percent_change(as.numeric(input_data[,2]),as.numeric(input_data[,3])),
  median_percent_change(as.numeric(input_data[,4]),as.numeric(input_data[,5])),
  median_percent_change(as.numeric(input_data[,16]),as.numeric(input_data[,17])),
  median_percent_change(as.numeric(input_data[,19]),as.numeric(input_data[,20])),
  median_percent_change(as.numeric(input_data[,6]),as.numeric(input_data[,7])),
  median_percent_change(as.numeric(input_data[,8]),as.numeric(input_data[,9])),
  median_percent_change(as.numeric(input_data[,17]),as.numeric(input_data[,18])),
  median_percent_change(as.numeric(input_data[,20]),as.numeric(input_data[,21]))
)
animal_percent_increase

#   -----------------------------------------------------------------
# additional calculations

# Number of studies (range, median, total)
c(min(animals_meta$n_of_studies),
  max(animals_meta$n_of_studies))
median(animals_meta$n_of_studies)
sum(animals_meta$n_of_studies)

# Animals per study
sample_size_in_study <-raw_data$n_treatment+raw_data$n_control
c(min(sample_size_in_study),max(sample_size_in_study))
median(sample_size_in_study)

med_n <- c()
min_n <- c()
max_n <- c()
for(i in unique(animals_meta$study_id)){
  med_n <- c(med_n,median(sample_size_in_study[raw_data$data_set==i]))
  min_n <- c(min_n,min(sample_size_in_study[raw_data$data_set==i]))
  max_n <- c(max_n,max(sample_size_in_study[raw_data$data_set==i]))
}
med_n
min_n
max_n
# Key numbers from meta analyses

meta_smd <- abs(animals_meta$estimate)
c(min(meta_smd),
  max(meta_smd))
median(meta_smd)

meta_tau2 <- abs(animals_meta$tau_squared)
c(min(meta_tau2),
  max(meta_tau2))
median(meta_tau2)

meta_i2 <- abs(animals_meta$i_squared)
c(min(meta_i2),
  max(meta_i2))
median(meta_i2)

#  Message Warnings for mixed model in percent
msg_warn <- (animals_out[,269]/100000)*100
mean(msg_warn) # 8% of cases
sum(msg_warn > 10) # 5 out of 28: more than 10% of cases
mean(msg_warn[msg_warn < 10]) # mean number of warnings in the remaining 23: 1.4 %
msg_warn 

animals_out_numeric <- as.data.frame(lapply(animals_out, type.convert, as.is = TRUE))

# TPR:
# Range for TPR: 13 - over 99%
c(min(animals_out_numeric[, 1:21]),
max(animals_out_numeric[, 1:21]))

# Edgington:
# Range for Edgington: 1 - over 99%
c(min(animals_out_numeric[,43:63]),
  max(animals_out_numeric[, 43:63]))

# Coverage:

# Highest Coverage reached by multi lab:98%
max(animals_out_numeric[,210+which(interventions=="multi lab")])
# Highest coverage reached by mid s 09: 21%
max(animals_out_numeric[,210+which(interventions=="mid s 09")])
# N of studies with multi lab coverage below 50%
sum((animals_out_numeric[,210+which(interventions=="multi lab")])<0.50)
  
# Power (aka TPR):
mean(animals_out_numeric[,1])
c(min(animals_out_numeric[,1]),
  max(animals_out_numeric[,1]))

sum(animals_meta$n_of_studies * animals_out_numeric[,1])/sum(animals_meta$n_of_studies)

# ----
#
# Sample Sizes

animals_samnple_sizes <- read.csv2("animals_sample_sizes.csv",sep=",",header = FALSE)


s_medians<-c()
s_min<-c()
s_max<-c()
for(i in 1:21){
  s_medians <- c(s_medians, median(as.numeric(animals_samnple_sizes[,i])))
  s_min <- c(s_min, min(as.numeric(animals_samnple_sizes[,i])))
  s_max <- c(s_max, max(as.numeric(animals_samnple_sizes[,i])))
}

h_sample <- data.frame(s_medians,s_min,s_max)
write.csv2(h_sample,"animal sample sizes summary.csv")

h_sample$variable <- factor(interventions, levels = interventions)


pdf(file="Animals sample sizes.pdf", paper="a4r", width=11)
ggplot(h_sample, aes(x = variable, y = s_medians, colour = variable)) +
  geom_linerange(aes(ymin = s_min, ymax = s_max), linewidth = 0.8) +
  geom_point(size = 2.5) +
  scale_y_log10() +
  scale_colour_manual(values = custom_palette, guide = "none") +
  theme_classic() +
  theme(aspect.ratio = 1/6,
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
  labs(x = "Intervention", y = "Sample Size")
dev.off()


animal_percent_increase <-c(
  100*(mean(as.numeric(animals_samnple_sizes[,3]))/mean(as.numeric(animals_samnple_sizes[,2]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,5]))/mean(as.numeric(animals_samnple_sizes[,4]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,17]))/mean(as.numeric(animals_samnple_sizes[,16]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,20]))/mean(as.numeric(animals_samnple_sizes[,19]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,7]))/mean(as.numeric(animals_samnple_sizes[,6]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,9]))/mean(as.numeric(animals_samnple_sizes[,8]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,18]))/mean(as.numeric(animals_samnple_sizes[,17]))-1),
  100*(mean(as.numeric(animals_samnple_sizes[,21]))/mean(as.numeric(animals_samnple_sizes[,20]))-1)
)

animal_percent_increase 

