################################################################################ # Rhythmicity as a welfare indicator in horses # Analysis script for Degree of Functional Coupling (DFC) # # Purpose: # This script reproduces the model selection, fixed-effect summaries, # model-based predictions, and figures used for the revised manuscript. # # Input: # horses_final.csv # # Main analysis: # - DFC is transformed using a power transformation: DFC^0.85 # - The global linear mixed-effects model includes treatment, standardized # mean daily lying duration, and experimental repetition as candidate # fixed effects. # - Random intercepts are included for group, horse nested within group, # and day number. # - Candidate models are ranked using AIC and BIC. # - The BIC-selected model is used as the primary model. # - The AIC-selected model is reported as a sensitivity analysis. # # Notes for reuse: # Place this script in the folder containing horses_final.csv, or set # data_dir below to the folder containing the input file. ################################################################################ ################################################################################ # 1. USER SETTINGS ################################################################################ # Folder containing horses_final.csv. Use "." for the current working directory. data_dir <- "." input_file <- file.path(data_dir, "horses_final.csv") output_dir <- file.path(data_dir, "analysis_outputs") excluded_row_ids <- c(39, 247, 258) lambda <- 0.85 bootstrap_seed <- 20260630 n_bootstrap <- 1000 ################################################################################ # 2. PACKAGES ################################################################################ required_packages <- c( "DHARMa", "MuMIn", "dplyr", "emmeans", "ggplot2", "lme4" ) missing_packages <- required_packages[ !vapply( required_packages, function(pkg) requireNamespace(pkg, quietly = TRUE), logical(1) ) ] if (length(missing_packages) > 0) { stop( paste( "Install the following packages before running this script:", paste(missing_packages, collapse = ", ") ), call. = FALSE ) } invisible( lapply(required_packages, library, character.only = TRUE) ) ################################################################################ # 3. HELPER FUNCTIONS ################################################################################ out_file <- function(filename) { file.path(output_dir, filename) } write_output_csv <- function(x, filename) { write.csv(x, out_file(filename), row.names = FALSE) } save_output_plot <- function(plot, filename, width = 7, height = 5, dpi = 600) { ggsave( filename = out_file(filename), plot = plot, width = width, height = height, dpi = dpi ) } inverse_power_transform <- function(x, lambda) { back_transformed <- pmax(x, 0)^(1 / lambda) pmin(pmax(back_transformed, 0), 1) } format_p_value <- function(p_value) { ifelse(p_value < 0.001, "<0.001", sprintf("%.3f", p_value)) } create_fixed_effects_table <- function(model, criterion) { model_summary <- coef(summary(model)) estimates <- model_summary[, "Estimate"] standard_errors <- model_summary[, "Std. Error"] z_values <- estimates / standard_errors data.frame( selected_by = criterion, term = rownames(model_summary), estimate = estimates, standard_error = standard_errors, confidence_interval_lower = estimates - 1.96 * standard_errors, confidence_interval_upper = estimates + 1.96 * standard_errors, z_value = z_values, p_value = 2 * pnorm(abs(z_values), lower.tail = FALSE), row.names = NULL ) } ################################################################################ # 4. LOAD AND PREPARE DATA ################################################################################ if (!file.exists(input_file)) { stop( paste("Input file not found:", input_file), call. = FALSE ) } if (!dir.exists(output_dir)) { dir.create(output_dir, recursive = TRUE) } raw_data <- read.csv(input_file, sep = ";") raw_data$row_id <- seq_len(nrow(raw_data)) required_columns <- c( "from", "to", "lying7sum", "group", "treatment", "horse.name", "day.number", "mean_lying_per_day_min", "DFC" ) missing_columns <- setdiff(required_columns, names(raw_data)) if (length(missing_columns) > 0) { stop( paste( "The input file is missing the following required columns:", paste(missing_columns, collapse = ", ") ), call. = FALSE ) } if ("THI" %in% names(raw_data)) { raw_data$THI <- as.numeric(raw_data$THI) } analysis_data <- raw_data %>% mutate( from = as.Date(from, format = "%d.%m.%Y"), to = as.Date(to, format = "%d.%m.%Y"), lying7sum = as.numeric(lying7sum), group = factor(group), treatment = factor(treatment, levels = c("adlib", "portion", "tradi")), horse.name = factor(horse.name), day.number = factor(day.number), repetition = factor( case_when( from >= as.Date("2023-02-04") & from <= as.Date("2023-03-12") ~ "Q1", from >= as.Date("2023-05-15") & from <= as.Date("2023-06-16") ~ "Q2", from >= as.Date("2023-06-17") & from <= as.Date("2023-07-14") ~ "Q3", TRUE ~ NA_character_ ), levels = c("Q1", "Q2", "Q3") ) ) excluded_observations <- analysis_data %>% filter(row_id %in% excluded_row_ids) write_output_csv(excluded_observations, "excluded_observations.csv") analysis_data <- analysis_data %>% filter(!row_id %in% excluded_row_ids) %>% droplevels() lying_center <- mean(analysis_data$mean_lying_per_day_min, na.rm = TRUE) lying_scale <- sd(analysis_data$mean_lying_per_day_min, na.rm = TRUE) if (is.na(lying_scale) || lying_scale == 0) { stop( "Mean daily lying duration cannot be standardized because its standard deviation is zero or missing.", call. = FALSE ) } analysis_data <- analysis_data %>% mutate( transformdfc = DFC^lambda, scaled_lying = (mean_lying_per_day_min - lying_center) / lying_scale, treatment_label = factor( treatment, levels = c("tradi", "portion", "adlib"), labels = c("3 feedings/day", "6 feedings/day", "ad libitum") ), treatment_plot = factor( treatment, levels = c("tradi", "portion", "adlib"), labels = c("3x/day", "6x/day", "adlib") ) ) model_variables <- c( "transformdfc", "treatment", "scaled_lying", "repetition", "group", "horse.name", "day.number" ) if (anyNA(analysis_data[model_variables])) { stop("Missing values remain in variables used for modelling.", call. = FALSE) } ################################################################################ # 5. GLOBAL MODEL AND MODEL DIAGNOSTICS ################################################################################ old_na_action <- getOption("na.action") options(na.action = "na.fail") on.exit(options(na.action = old_na_action), add = TRUE) global_model <- lmer( transformdfc ~ treatment + scaled_lying + repetition + (1 | group / horse.name) + (1 | day.number), data = analysis_data, REML = FALSE, na.action = na.fail ) simulation_residuals <- simulateResiduals( fittedModel = global_model, plot = FALSE ) pdf(out_file("global_model_diagnostics.pdf"), width = 8, height = 8) plot(simulation_residuals) dev.off() ################################################################################ # 6. MODEL SELECTION ################################################################################ model_selection_AIC <- dredge( global_model, rank = "AIC", trace = FALSE ) model_selection_BIC <- dredge( global_model, rank = "BIC", trace = FALSE ) model_selection_AIC_table <- as.data.frame(model_selection_AIC) model_selection_AIC_table$model_rank <- seq_len(nrow(model_selection_AIC_table)) model_selection_BIC_table <- as.data.frame(model_selection_BIC) model_selection_BIC_table$model_rank <- seq_len(nrow(model_selection_BIC_table)) write_output_csv(model_selection_AIC_table, "model_selection_AIC_all_models.csv") write_output_csv(model_selection_BIC_table, "model_selection_BIC_all_models.csv") best_model_AIC <- get.models(model_selection_AIC, 1)[[1]] best_model_BIC <- get.models(model_selection_BIC, 1)[[1]] primary_model <- best_model_BIC best_AIC <- model_selection_AIC$AIC[1] second_AIC <- model_selection_AIC$AIC[2] delta_AIC <- second_AIC - best_AIC AIC_evidence_ratio <- exp(delta_AIC / 2) best_BIC <- model_selection_BIC$BIC[1] second_BIC <- model_selection_BIC$BIC[2] delta_BIC <- second_BIC - best_BIC BIC_evidence_ratio <- exp(delta_BIC / 2) model_selection_summary <- data.frame( criterion = c("AIC", "BIC"), best_value = c(best_AIC, best_BIC), second_value = c(second_AIC, second_BIC), delta = c(delta_AIC, delta_BIC), evidence_ratio = c(AIC_evidence_ratio, BIC_evidence_ratio), selected_formula = c( paste(deparse(formula(best_model_AIC)), collapse = " "), paste(deparse(formula(best_model_BIC)), collapse = " ") ) ) write_output_csv(model_selection_summary, "model_selection_summary.csv") ################################################################################ # 7. MODEL SUMMARIES AND FIXED EFFECTS ################################################################################ primary_model_summary <- data.frame( primary_criterion = "BIC", formula = paste(deparse(formula(primary_model)), collapse = " "), observations = nobs(primary_model), log_likelihood = as.numeric(logLik(primary_model)), AIC = AIC(primary_model), BIC = BIC(primary_model), singular_fit = isSingular(primary_model) ) write_output_csv(primary_model_summary, "primary_model_summary_BIC.csv") fixed_effects_AIC <- create_fixed_effects_table(best_model_AIC, "AIC") fixed_effects_BIC <- create_fixed_effects_table(best_model_BIC, "BIC") fixed_effects_combined <- bind_rows( fixed_effects_AIC, fixed_effects_BIC ) write_output_csv(fixed_effects_BIC, "fixed_effects_primary_BIC.csv") write_output_csv(fixed_effects_combined, "fixed_effects_AIC_BIC.csv") fixed_effects_text <- fixed_effects_combined %>% mutate( significance = case_when( p_value < 0.001 ~ "***", p_value < 0.01 ~ "**", p_value < 0.05 ~ "*", TRUE ~ "" ), estimate_standard_error = sprintf( "%.3f%s (%.3f)", estimate, significance, standard_error ), confidence_interval = sprintf( "[%.3f, %.3f]", confidence_interval_lower, confidence_interval_upper ), p_value_formatted = format_p_value(p_value) ) %>% dplyr::select( selected_by, term, estimate_standard_error, confidence_interval, p_value_formatted ) write.table( fixed_effects_text, file = out_file("fixed_effects_AIC_BIC.txt"), sep = "\t", row.names = FALSE, quote = FALSE ) model_diagnostics_summary <- data.frame( model = c("Global model", "AIC-selected model", "BIC-selected model"), singular_fit = c( isSingular(global_model), isSingular(best_model_AIC), isSingular(best_model_BIC) ), observations = c( nobs(global_model), nobs(best_model_AIC), nobs(best_model_BIC) ), log_likelihood = c( as.numeric(logLik(global_model)), as.numeric(logLik(best_model_AIC)), as.numeric(logLik(best_model_BIC)) ), AIC = c( AIC(global_model), AIC(best_model_AIC), AIC(best_model_BIC) ), BIC = c( BIC(global_model), BIC(best_model_AIC), BIC(best_model_BIC) ) ) write_output_csv(model_diagnostics_summary, "model_diagnostics_summary.csv") data_summary <- data.frame( observations = nrow(analysis_data), horses = nlevels(analysis_data$horse.name), groups = nlevels(analysis_data$group), excluded_observations = nrow(excluded_observations), lying_duration_minimum = min(analysis_data$mean_lying_per_day_min), lying_duration_median = median(analysis_data$mean_lying_per_day_min), lying_duration_mean = mean(analysis_data$mean_lying_per_day_min), lying_duration_standard_deviation = sd(analysis_data$mean_lying_per_day_min), lying_duration_maximum = max(analysis_data$mean_lying_per_day_min), DFC_minimum = min(analysis_data$DFC), DFC_median = median(analysis_data$DFC), DFC_mean = mean(analysis_data$DFC), DFC_standard_deviation = sd(analysis_data$DFC), DFC_maximum = max(analysis_data$DFC) ) write_output_csv(data_summary, "data_summary.csv") ################################################################################ # 8. MODEL-BASED PREDICTIONS FOR LYING DURATION ################################################################################ lying_values <- seq( min(analysis_data$mean_lying_per_day_min), max(analysis_data$mean_lying_per_day_min), length.out = 200 ) primary_model_terms <- attr(terms(primary_model), "term.labels") prediction_repetitions <- if ("repetition" %in% primary_model_terms) { levels(analysis_data$repetition) } else { levels(analysis_data$repetition)[1] } lying_prediction_grid <- expand.grid( mean_lying_per_day_min = lying_values, treatment = levels(analysis_data$treatment), repetition = prediction_repetitions, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE ) lying_prediction_grid <- lying_prediction_grid %>% mutate( scaled_lying = (mean_lying_per_day_min - lying_center) / lying_scale, treatment = factor(treatment, levels = levels(analysis_data$treatment)), repetition = factor(repetition, levels = levels(analysis_data$repetition)), group = factor(levels(analysis_data$group)[1], levels = levels(analysis_data$group)), horse.name = factor( levels(analysis_data$horse.name)[1], levels = levels(analysis_data$horse.name) ), day.number = factor( levels(analysis_data$day.number)[1], levels = levels(analysis_data$day.number) ), lying_index = match(mean_lying_per_day_min, lying_values) ) predict_lying_marginal <- function(model) { predictions <- predict( model, newdata = lying_prediction_grid, re.form = NA, allow.new.levels = TRUE ) as.numeric( tapply(predictions, lying_prediction_grid$lying_index, mean) ) } set.seed(bootstrap_seed) lying_predictions_transformed <- predict_lying_marginal(primary_model) lying_bootstrap <- bootMer( primary_model, FUN = predict_lying_marginal, nsim = n_bootstrap, type = "parametric", use.u = FALSE, parallel = "no" ) lying_bootstrap_confidence_intervals <- t( apply( lying_bootstrap$t, 2, quantile, probs = c(0.025, 0.975), na.rm = TRUE ) ) lying_predictions_marginal <- data.frame( mean_lying_per_day_min = lying_values, estimate_transformed = lying_predictions_transformed, confidence_interval_lower_transformed = lying_bootstrap_confidence_intervals[, 1], confidence_interval_upper_transformed = lying_bootstrap_confidence_intervals[, 2] ) %>% mutate( estimate_DFC = inverse_power_transform(estimate_transformed, lambda), confidence_interval_lower_DFC = inverse_power_transform( confidence_interval_lower_transformed, lambda ), confidence_interval_upper_DFC = inverse_power_transform( confidence_interval_upper_transformed, lambda ) ) write_output_csv( lying_predictions_marginal, "lying_duration_predictions_marginal_BIC.csv" ) ################################################################################ # 9. MODEL-BASED PREDICTIONS BY TREATMENT ################################################################################ lying_prediction_grid_by_treatment <- expand.grid( mean_lying_per_day_min = lying_values, treatment = levels(analysis_data$treatment), repetition = prediction_repetitions, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE ) lying_prediction_grid_by_treatment <- lying_prediction_grid_by_treatment %>% mutate( scaled_lying = (mean_lying_per_day_min - lying_center) / lying_scale, treatment = factor(treatment, levels = levels(analysis_data$treatment)), repetition = factor(repetition, levels = levels(analysis_data$repetition)), group = factor(levels(analysis_data$group)[1], levels = levels(analysis_data$group)), horse.name = factor( levels(analysis_data$horse.name)[1], levels = levels(analysis_data$horse.name) ), day.number = factor( levels(analysis_data$day.number)[1], levels = levels(analysis_data$day.number) ), prediction_group = interaction( mean_lying_per_day_min, treatment, drop = TRUE, lex.order = TRUE ) ) prediction_group_levels <- levels( lying_prediction_grid_by_treatment$prediction_group ) predict_lying_by_treatment <- function(model) { predictions <- predict( model, newdata = lying_prediction_grid_by_treatment, re.form = NA, allow.new.levels = TRUE ) grouped_predictions <- tapply( predictions, lying_prediction_grid_by_treatment$prediction_group, mean ) as.numeric(grouped_predictions[prediction_group_levels]) } set.seed(bootstrap_seed) lying_predictions_by_treatment_transformed <- predict_lying_by_treatment( primary_model ) lying_by_treatment_bootstrap <- bootMer( primary_model, FUN = predict_lying_by_treatment, nsim = n_bootstrap, type = "parametric", use.u = FALSE, parallel = "no" ) lying_by_treatment_confidence_intervals <- t( apply( lying_by_treatment_bootstrap$t, 2, quantile, probs = c(0.025, 0.975), na.rm = TRUE ) ) lying_predictions_by_treatment_keys <- lying_prediction_grid_by_treatment %>% distinct( prediction_group, mean_lying_per_day_min, treatment ) %>% arrange( factor(prediction_group, levels = prediction_group_levels) ) lying_predictions_by_treatment <- lying_predictions_by_treatment_keys %>% mutate( estimate_transformed = lying_predictions_by_treatment_transformed, confidence_interval_lower_transformed = lying_by_treatment_confidence_intervals[, 1], confidence_interval_upper_transformed = lying_by_treatment_confidence_intervals[, 2], estimate_DFC = inverse_power_transform(estimate_transformed, lambda), confidence_interval_lower_DFC = inverse_power_transform( confidence_interval_lower_transformed, lambda ), confidence_interval_upper_DFC = inverse_power_transform( confidence_interval_upper_transformed, lambda ), treatment_label = factor( treatment, levels = c("tradi", "portion", "adlib"), labels = c("3 feedings/day", "6 feedings/day", "ad libitum") ) ) write_output_csv( lying_predictions_by_treatment, "lying_duration_predictions_by_treatment_BIC.csv" ) ################################################################################ # 10. ESTIMATED MARGINAL MEANS AND TREATMENT COMPARISONS ################################################################################ treatment_emmeans <- emmeans( primary_model, ~ treatment, at = list(scaled_lying = 0), weights = "equal" ) treatment_emmeans_table <- as.data.frame( confint(treatment_emmeans, level = 0.95) ) %>% mutate( estimate_DFC = inverse_power_transform(emmean, lambda), confidence_interval_lower_DFC = inverse_power_transform(lower.CL, lambda), confidence_interval_upper_DFC = inverse_power_transform(upper.CL, lambda), treatment_label = factor( treatment, levels = c("tradi", "portion", "adlib"), labels = c("3 feedings/day", "6 feedings/day", "ad libitum") ), treatment_plot = factor( treatment, levels = c("tradi", "portion", "adlib"), labels = c("3x/day", "6x/day", "adlib") ) ) write_output_csv( treatment_emmeans_table, "treatment_estimated_marginal_means_BIC.csv" ) treatment_pairwise_comparisons <- as.data.frame( summary( pairs(treatment_emmeans, adjust = "tukey"), infer = c(TRUE, TRUE) ) ) write_output_csv( treatment_pairwise_comparisons, "treatment_pairwise_comparisons_BIC.csv" ) ################################################################################ # 11. FIGURES: PUBLICATION-STYLE VERSION ################################################################################ publication_colours <- c( "3 feedings/day" = "coral", "6 feedings/day" = "gold1", "ad libitum" = "darkolivegreen3" ) plot_lying_DFC_publication <- ggplot( analysis_data, aes( x = mean_lying_per_day_min, y = DFC ) ) + geom_point( aes(shape = "Raw data"), color = "black", size = 1.5, alpha = 0.7 ) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = estimate_DFC, color = "Central estimate", linetype = "Central estimate" ), inherit.aes = FALSE, linewidth = 1 ) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = confidence_interval_lower_DFC, color = "95% confidence limits", linetype = "95% confidence limits" ), inherit.aes = FALSE, linewidth = 0.8 ) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = confidence_interval_upper_DFC, color = "95% confidence limits", linetype = "95% confidence limits" ), inherit.aes = FALSE, linewidth = 0.8 ) + scale_shape_manual(values = c("Raw data" = 16)) + scale_color_manual( values = c( "Central estimate" = "red", "95% confidence limits" = "blue" ) ) + scale_linetype_manual( values = c( "Central estimate" = "solid", "95% confidence limits" = "dashed" ) ) + coord_cartesian(ylim = c(0, 1)) + labs( title = "Relationship between lying duration and DFC", x = "Mean lying duration per day [min]", y = "DFC", shape = NULL, color = NULL, linetype = NULL ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 16), axis.title.y = element_text(size = 16), axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12), legend.position = "bottom", legend.box = "horizontal" ) save_output_plot( plot_lying_DFC_publication, "lying_duration_predictions_marginal_BIC.pdf" ) save_output_plot( plot_lying_DFC_publication, "lying_duration_predictions_marginal_BIC.png" ) plot_lying_DFC_by_treatment_publication <- ggplot( analysis_data, aes( x = mean_lying_per_day_min, y = DFC, color = treatment_label ) ) + geom_point(size = 1.2, alpha = 0.45) + geom_ribbon( data = lying_predictions_by_treatment, aes( x = mean_lying_per_day_min, ymin = confidence_interval_lower_DFC, ymax = confidence_interval_upper_DFC, fill = treatment_label, group = treatment_label ), inherit.aes = FALSE, alpha = 0.15 ) + geom_line( data = lying_predictions_by_treatment, aes( x = mean_lying_per_day_min, y = estimate_DFC, color = treatment_label, group = treatment_label ), inherit.aes = FALSE, linewidth = 1 ) + scale_color_manual(values = publication_colours) + scale_fill_manual(values = publication_colours) + coord_cartesian(ylim = c(0, 1)) + labs( title = "Relationship between lying duration and DFC by feeding regime", x = "Mean lying duration per day [min]", y = "DFC", color = "Feeding regime", fill = "Feeding regime" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 16), axis.title.y = element_text(size = 16), axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12), legend.position = "bottom" ) save_output_plot( plot_lying_DFC_by_treatment_publication, "lying_duration_predictions_by_treatment_BIC.pdf" ) save_output_plot( plot_lying_DFC_by_treatment_publication, "lying_duration_predictions_by_treatment_BIC.png" ) plot_treatment_DFC_publication <- ggplot( analysis_data, aes( x = treatment_label, y = DFC, fill = treatment_label ) ) + geom_boxplot(width = 0.5, outlier.shape = NA) + geom_jitter( aes(shape = "Raw data"), height = 0, width = 0.1, alpha = 0.35, size = 1.3, color = "black" ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_label, y = estimate_DFC, shape = "Central estimate" ), inherit.aes = FALSE, color = "red", fill = "red", size = 3, stroke = 1 ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_label, y = confidence_interval_lower_DFC, shape = "Lower 95% confidence limit" ), inherit.aes = FALSE, color = "blue", fill = "blue", size = 3, stroke = 1 ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_label, y = confidence_interval_upper_DFC, shape = "Upper 95% confidence limit" ), inherit.aes = FALSE, color = "blue", fill = "blue", size = 3, stroke = 1 ) + scale_fill_manual(values = publication_colours) + scale_shape_manual( values = c( "Raw data" = 16, "Central estimate" = 22, "Lower 95% confidence limit" = 25, "Upper 95% confidence limit" = 24 ) ) + coord_cartesian(ylim = c(0, 1)) + labs( title = "Relationship between feeding regime and DFC", x = "Feeding regime", y = "DFC", shape = NULL ) + guides( fill = "none", shape = guide_legend( nrow = 1, byrow = TRUE, override.aes = list( color = c("black", "red", "blue", "blue"), fill = c("black", "red", "blue", "blue"), alpha = 1, size = 3 ) ) ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14), axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12), legend.position = "bottom" ) save_output_plot(plot_treatment_DFC_publication, "treatment_predictions_BIC.pdf") save_output_plot(plot_treatment_DFC_publication, "treatment_predictions_BIC.png") plot_lying_treatment_publication <- ggplot( analysis_data, aes( x = treatment_label, y = mean_lying_per_day_min, fill = treatment_label ) ) + geom_boxplot(width = 0.5) + scale_fill_manual(values = publication_colours) + labs( title = "Relationship between mean lying duration and feeding regime", x = "Feeding regime", y = "Mean lying duration per day [min]" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 16), axis.title.y = element_text(size = 16), axis.text.x = element_text(size = 16), axis.text.y = element_text(size = 16), legend.position = "none" ) save_output_plot(plot_lying_treatment_publication, "lying_duration_by_treatment.pdf") save_output_plot(plot_lying_treatment_publication, "lying_duration_by_treatment.png") ################################################################################ # 12. FIGURES: ORIGINAL MANUSCRIPT LAYOUTS USING FINAL DATA AND BIC RESULTS ################################################################################ original_plot_colours <- c( "3x/day" = "coral", "6x/day" = "gold1", "adlib" = "darkolivegreen3" ) plot_lying_DFC_original <- ggplot() + geom_jitter( data = analysis_data, aes( x = mean_lying_per_day_min, y = DFC ), height = 0, width = 0.1 ) + theme_minimal() + coord_cartesian(ylim = c(0, 1)) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = estimate_DFC ) ) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = confidence_interval_lower_DFC ), linetype = "dashed" ) + geom_line( data = lying_predictions_marginal, aes( x = mean_lying_per_day_min, y = confidence_interval_upper_DFC ), linetype = "dashed" ) + labs( title = "Relationship between lying duration and DFC", x = "Mean lying duration per day [min]", y = "DFC" ) + theme( plot.title = element_text(hjust = 0.5) ) save_output_plot( plot_lying_DFC_original, "Figure_lying_duration_BIC_old_layout.pdf" ) save_output_plot( plot_lying_DFC_original, "Figure_lying_duration_BIC_old_layout.png" ) plot_lying_treatment_original <- ggplot( analysis_data, aes( x = treatment_plot, y = mean_lying_per_day_min, fill = treatment_plot ) ) + geom_boxplot(width = 0.5) + scale_fill_manual(values = original_plot_colours) + theme_minimal() + labs( title = "Relationship between mean lying duration and feeding regime", x = "Feeding regime", y = "Mean lying duration per day [min]" ) + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 16), axis.title.y = element_text(size = 16), axis.text.x = element_text(size = 16), axis.text.y = element_text(size = 16), legend.position = "none" ) save_output_plot( plot_lying_treatment_original, "Figure_lying_duration_by_treatment_old_layout.pdf" ) save_output_plot( plot_lying_treatment_original, "Figure_lying_duration_by_treatment_old_layout.png" ) plot_treatment_DFC_original <- ggplot() + geom_boxplot( data = analysis_data, aes( x = treatment_plot, y = DFC, fill = treatment_plot ), width = 0.5 ) + geom_jitter( data = analysis_data, aes( x = treatment_plot, y = DFC ), height = 0, width = 0.1, alpha = 0.2, colour = "black" ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_plot, y = estimate_DFC ), colour = "red", fill = "red", shape = 22, size = 2, stroke = 1.5 ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_plot, y = confidence_interval_lower_DFC ), colour = "blue", fill = "blue", shape = 25, size = 2, stroke = 1.5 ) + geom_point( data = treatment_emmeans_table, aes( x = treatment_plot, y = confidence_interval_upper_DFC ), colour = "blue", fill = "blue", shape = 24, size = 2, stroke = 1.5 ) + scale_fill_manual(values = original_plot_colours) + coord_cartesian(ylim = c(0, 1)) + theme_minimal() + labs( title = "Relationship between feeding regime and DFC", x = "Feeding regime", y = "DFC" ) + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14), axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12), legend.position = "none" ) save_output_plot(plot_treatment_DFC_original, "Figure_5_BIC_old_layout.pdf") save_output_plot(plot_treatment_DFC_original, "Figure_5_BIC_old_layout.png") plot_treatment_group_original <- ggplot( analysis_data, aes( x = treatment_plot, y = DFC, fill = treatment_plot ) ) + geom_boxplot() + facet_wrap(~ group) + labs( title = "Comparison of DFC by feeding regime and group", x = "Feeding regime", y = "DFC" ) + scale_fill_manual(values = original_plot_colours) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14), legend.position = "none" ) save_output_plot( plot_treatment_group_original, "Figure_DFC_by_treatment_and_group_old_layout.pdf", width = 8, height = 5 ) save_output_plot( plot_treatment_group_original, "Figure_DFC_by_treatment_and_group_old_layout.png", width = 8, height = 5 ) ################################################################################ # 13. SAVE MODELS AND SESSION INFORMATION ################################################################################ saveRDS(best_model_AIC, out_file("best_model_AIC.rds")) saveRDS(best_model_BIC, out_file("best_model_BIC.rds")) capture.output( sessionInfo(), file = out_file("session_info.txt") ) ################################################################################ # 14. PRINT KEY OUTPUTS ################################################################################ message("Analysis completed. Outputs written to: ", normalizePath(output_dir)) print(model_selection_summary) print(fixed_effects_combined) print(data_summary) print(lying_predictions_marginal) print(treatment_emmeans_table) print(treatment_pairwise_comparisons) print(primary_model_summary)