Nantes Université

Skip to content
Extraits de code Groupes Projets
Valider db934354 rédigé par Ahmed CHOUKRI's avatar Ahmed CHOUKRI :speech_balloon:
Parcourir les fichiers

new scripts

parent 2956e880
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
^renv$
^renv\.lock$
^.*\.Rproj$
^\.Rproj\.user$
source("renv/activate.R")
.Rproj.user
.Rhistory
.RData
.Ruserdata
Version: 1.0
RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default
EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8
RnwWeave: Sweave
LaTeX: pdfLaTeX
AutoAppendNewline: Yes
StripTrailingWhitespace: Yes
BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
Package: AMAP
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.3.2
exportPattern("^[[:alpha:]]+")
#' Import and Prepare Data
#'
#' This function imports data from an Excel file and ensures that the `WPI` column is set as a factor.
#'
#' @param file_path A string indicating the file path to the Excel file to be imported.
#'
#' @return A data frame with the imported data where `WPI` is converted to a factor.
#' @export
import_and_prepare_data <- function(file_path) {
# Import data from Excel
data <- read_excel(file_path)
# Ensure WPI is a factor
data <- data %>%
mutate(WPI = as.factor(WPI))
return(data)
}
#' Fit and Evaluate Distributions for Relative Germination Data
#'
#' This function adjusts the relative germination values if necessary, fits multiple distributions,
#' evaluates goodness-of-fit statistics, and plots each fitted distribution for visual inspection.
#'
#' @param data A data frame containing a column `relative.germination` with numeric values.
#'
#' @return A list containing fitted distribution objects and goodness-of-fit statistics.
#' @export
#'
#' @examples
#' # Example usage:
#' data <- read_excel("C:/Users/Choukri-A/Desktop/HPLC/AMAP/test.xlsx")
#' data$WPI <- as.factor(data$WPI)
#' fit_results <- fit_and_evaluate_distributions(data)
library(fitdistrplus)
library(ggplot2)
fit_and_evaluate_distributions <- function(data) {
# Adjust values for Beta distribution if needed
data$relative.germination <- ifelse(data$relative.germination == 0, 0.001, data$relative.germination)
data$relative.germination <- ifelse(data$relative.germination == 1, 0.999, data$relative.germination)
# Fit various distributions
fits <- list(
normal = fitdist(data$relative.germination, "norm"),
exponential = fitdist(data$relative.germination, "exp"),
gamma = fitdist(data$relative.germination[data$relative.germination > 0], "gamma"),
log_normal = fitdist(data$relative.germination[data$relative.germination > 0], "lnorm"),
weibull = fitdist(data$relative.germination[data$relative.germination > 0], "weibull"),
cauchy = fitdist(data$relative.germination, "cauchy")
)
# Fit Beta distribution if all values are in (0, 1)
if (all(data$relative.germination > 0 & data$relative.germination < 1)) {
fits$beta <- fitdist(data$relative.germination, "beta")
} else {
warning("Skipping Beta distribution as data is not within (0, 1).")
}
# Print summaries of each distribution
summaries <- lapply(fits, summary)
print(summaries)
# Plot all fits using ggplot2
plot_list <- list()
for (fit_name in names(fits)) {
fit <- fits[[fit_name]]
denscomp_plot <- denscomp(list(fit), plotstyle = "ggplot") +
ggtitle(paste(fit_name, "fit")) +
theme_minimal()
plot_list[[fit_name]] <- denscomp_plot
}
# Arrange plots in a grid
grid_plot <- ggarrange(plotlist = plot_list, ncol = 2, nrow = 3)
print(grid_plot)
# Goodness-of-fit statistics for comparison
gof <- gofstat(fits)
print(gof)
return(list(fits = fits, summaries = summaries, gof = gof, plots = plot_list))
}
# Hello, world!
#
# This is an example function named 'hello'
# which prints 'Hello, world!'.
#
# You can learn more about package authoring with RStudio at:
#
# http://r-pkgs.had.co.nz/
#
# Some useful keyboard shortcuts for package authoring:
#
# Install Package: 'Ctrl + Shift + B'
# Check Package: 'Ctrl + Shift + E'
# Test Package: 'Ctrl + Shift + T'
hello <- function() {
print("Hello, world!")
}
# Load required packages
if(!require("fitdistrplus")) install.packages("fitdistrplus", dependencies = TRUE)
if(!require("readxl")) install.packages("readxl", dependencies = TRUE)
library(fitdistrplus)
library(readxl)
library(dplyr)
#' Plot Germination Ratio with Mean and Standard Deviation
#'
#' This function reads in data, calculates summary statistics (mean and standard deviation),
#' and plots the germination ratio for each Genotype across Weeks Post-Inoculation (WPI).
#'
#' @param data A data frame containing columns `Genotype`, `WPI`, and `relative.germination`.
#' @param y_scale A numeric vector specifying the y-axis limits, default is `c(0, 1.2)`.
#' @param custom_colors A character vector of colors to use for each Genotype.
#' @param dodge_width A numeric value for dodging width, default is `0.3`.
#'
#' @return A ggplot object displaying germination ratio means with standard deviation error bars.
#' @export
#'
#' @examples
#' # Example usage:
#' data <- read_excel("C:/Users/Choukri-A/Desktop/HPLC/AMAP/test.xlsx")
#' data$WPI <- as.factor(data$WPI)
#' plot_germination(data)
plot_germination <- function(data, model_summary, y_scale = c(0, 1.2),
custom_colors = c("#FF0000", "#00FF00", "#0000FF", "#800080", "#FF00FF", "#00FFFF"),
dodge_width = 0.3) {
# Summarize data by calculating mean and standard deviation
summary_data <- data %>%
group_by(Genotype, WPI) %>%
summarise(
mean_germination = mean(relative.germination, na.rm = TRUE),
sd_germination = sd(relative.germination, na.rm = TRUE)
)
# Extract p-values from GLM results
p_values <- model_summary$coefficients[, "Pr(>|t|)"]
coefficients <- rownames(model_summary$coefficients)
# Determine significance levels
significance_levels <- ifelse(p_values < 0.0001, "***",
ifelse(p_values < 0.001, "**",
ifelse(p_values < 0.05, "*", "")))
# Create a data frame for significance annotations
sig_annotations <- data.frame(
coefficient = coefficients,
significance = significance_levels,
stringsAsFactors = FALSE
)
# Print the significance annotations
print(sig_annotations)
# Create the plot
p <- ggplot(summary_data, aes(x = factor(WPI),
y = mean_germination,
group = Genotype,
color = factor(Genotype, levels = unique(Genotype)))) +
geom_line(position = position_dodge(width = dodge_width), size = 1.2) +
geom_point(position = position_dodge(width = dodge_width), size = 3) +
geom_errorbar(aes(ymin = mean_germination - sd_germination, ymax = mean_germination + sd_germination),
position = position_dodge(width = dodge_width),
width = 0.2,
size = 1,
color = "black") +
labs(
x = "Weeks Post-Inoculation (WPI)",
y = "Germination ratio",
color = "Genotype"
) +
theme_minimal() +
theme(
axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 14),
axis.title = element_text(face = "bold", size = 14),
axis.text.y = element_text(size = 11),
axis.title.y = element_text(face = "bold", size = 14),
plot.title = element_text(face = "bold", size = 16),
legend.title = element_text(size = 16),
legend.text = element_text(face = "italic", size = 16),
panel.grid.major = element_line(color = "gray", linetype = "dashed"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
strip.text = element_text(size = 12, face = "bold")
) +
scale_color_manual(values = custom_colors) +
coord_cartesian(ylim = y_scale) +
scale_x_discrete(limits = c("1", "2", "3", "4"))
# Add significance asterisks at the mean points
for (i in 1:nrow(sig_annotations)) {
if (!is.na(sig_annotations$significance[i]) && sig_annotations$significance[i] != "") {
coefficient <- sig_annotations$coefficient[i]
if (grepl("WPI", coefficient)) {
wpi <- as.numeric(gsub("WPI", "", coefficient))
genotype <- "Intercept"
} else {
genotype <- gsub("Genotype", "", coefficient)
wpi <- 1
}
mean_value <- summary_data %>%
filter(WPI == wpi & Genotype == genotype) %>%
pull(mean_germination)
if (length(mean_value) > 0) {
p <- p + annotate("text", x = wpi, y = mean_value + 0.05,
label = sig_annotations$significance[i], size = 6, color = "black")
}
}
}
# Display plot
print(p)
# Return the ggplot object
return(p)
}
#' Fit GLM and Perform Post Hoc Analysis for Relative Germination Data
#'
#' This function fits a generalized linear model (GLM) for `relative.germination` based on `WPI` and `Genotype`,
#' calculates estimated marginal means, and performs a Tukey post hoc test for pairwise comparisons.
#'
#' @param data A data frame containing columns `relative.germination`, `WPI`, and `Genotype`.
#' @param family The family for the GLM; default is Gamma with a log link.
#'
#' @return A list containing the model summary, estimated marginal means, and Tukey post hoc test results.
#' @export
#'
#' @examples
#' # Example usage:
#' data <- read_excel("C:/Users/Choukri-A/Desktop/HPLC/AMAP/test.xlsx")
#' data$WPI <- as.factor(data$WPI)
#' glm_results <- fit_glm_and_posthoc(data)
fit_glm_and_posthoc <- function(data, family = Gamma(link = "log")) {
# Load necessary libraries
library(stats)
library(emmeans)
# Fit the generalized linear model
model <- glm(relative.germination ~ WPI * Genotype, data = data, family = family)
# Summarize the model
model_summary <- summary(model)
print(model_summary)
# Check model diagnostics
plot(model)
# Calculate estimated marginal means for the interaction of WPI and Genotype
emm <- emmeans(model, ~ WPI * Genotype)
print(emm)
# Perform Tukey's post hoc test for the interaction of WPI and Genotype
tukey_result <- pairs(emm, adjust = "tukey")
print(tukey_result)
# Return the model, marginal means, and Tukey results
return(list(
model_summary = model_summary,
emm = emm,
tukey_result = tukey_result
))
}
......@@ -2,92 +2,17 @@
## Getting started
## Main commands
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.univ-nantes.fr/rhizoplante_experiments_r_registery/minirhizotrons.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.univ-nantes.fr/rhizoplante_experiments_r_registery/minirhizotrons/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
library(AMAP)
prepared_data <- import_and_prepare_data(choose.files())
fit_results <- fit_and_evaluate_distributions(data)
glm_results <- fit_glm_and_posthoc(data)
plot_germination(data, model_summary)
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
```
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/distribution analysis.R
\name{fit_and_evaluate_distributions}
\alias{fit_and_evaluate_distributions}
\title{Fit and Evaluate Distributions for Relative Germination Data}
\usage{
fit_and_evaluate_distributions(data)
}
\arguments{
\item{data}{A data frame containing a column `relative.germination` with numeric values.}
}
\value{
A list containing fitted distribution objects and goodness-of-fit statistics.
}
\description{
This function adjusts the relative germination values if necessary, fits multiple distributions,
evaluates goodness-of-fit statistics, and plots each fitted distribution for visual inspection.
}
\examples{
# Example usage:
data <- read_excel("C:/Users/Choukri-A/Desktop/HPLC/AMAP/test.xlsx")
data$WPI <- as.factor(data$WPI)
fit_results <- fit_and_evaluate_distributions(data)
}
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/statistical_analysis.R
\name{fit_glm_and_posthoc}
\alias{fit_glm_and_posthoc}
\title{Fit GLM and Perform Post Hoc Analysis for Relative Germination Data}
\usage{
fit_glm_and_posthoc(data, family = Gamma(link = "log"))
}
\arguments{
\item{data}{A data frame containing columns `relative.germination`, `WPI`, and `Genotype`.}
\item{family}{The family for the GLM; default is Gamma with a log link.}
}
\value{
A list containing the model summary, estimated marginal means, and Tukey post hoc test results.
}
\description{
This function fits a generalized linear model (GLM) for `relative.germination` based on `WPI` and `Genotype`,
calculates estimated marginal means, and performs a Tukey post hoc test for pairwise comparisons.
}
\examples{
# Example usage:
data <- read_excel("C:/Users/Choukri-A/Desktop/HPLC/AMAP/test.xlsx")
data$WPI <- as.factor(data$WPI)
glm_results <- fit_glm_and_posthoc(data)
}
\name{hello}
\alias{hello}
\title{Hello, World!}
\usage{
hello()
}
\description{
Prints 'Hello, world!'.
}
\examples{
hello()
}
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter