if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("phyloseq")
## Bioconductor version 3.18 (BiocManager 1.30.23), R 4.3.0 (2023-04-21 ucrt)
## Warning: package(s) not installed when version(s) same as or greater than current; use
##   `force = TRUE` to re-install: 'phyloseq'
## Installation paths not writeable, unable to update packages
##   path: C:/Program Files/R/R-4.3.0/library
##   packages:
##     boot, class, cluster, codetools, foreign, KernSmooth, lattice, mgcv, nlme,
##     nnet, rpart, spatial, survival
## Old packages: 'lavaan'
chooseCRANmirror(ind = 1)  # Elige un espejo de CRAN de la lista
install.packages("phyloseq", dependencies = TRUE)
## Installing package into 'C:/Users/HP/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## Warning: package 'phyloseq' is not available for this version of R
## 
## A version of this package for your version of R might be available elsewhere,
## see the ideas at
## https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
install.packages("phyloseq")
## Installing package into 'C:/Users/HP/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## Warning: package 'phyloseq' is not available for this version of R
## 
## A version of this package for your version of R might be available elsewhere,
## see the ideas at
## https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
library(phyloseq)
## Warning: package 'phyloseq' was built under R version 4.3.1
## Warning in .recacheSubclasses(def@className, def, env): undefined subclass
## "pcorMatrix" of class "mMatrix"; definition not updated
install.packages("vegan")
## Installing package into 'C:/Users/HP/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'vegan' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'vegan'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\HP\AppData\Local\R\win-library\4.3\00LOCK\vegan\libs\x64\vegan.dll a
## C:\Users\HP\AppData\Local\R\win-library\4.3\vegan\libs\x64\vegan.dll:
## Permission denied
## Warning: restored 'vegan'
## 
## The downloaded binary packages are in
##  C:\Users\HP\AppData\Local\Temp\RtmpaYELK6\downloaded_packages
library(vegan)
## Warning: package 'vegan' was built under R version 4.3.3
## Loading required package: permute
## Warning: package 'permute' was built under R version 4.3.3
## Loading required package: lattice
## This is vegan 2.6-6.1
install.packages("DESeq2")
## Installing package into 'C:/Users/HP/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## Warning: package 'DESeq2' is not available for this version of R
## 
## A version of this package for your version of R might be available elsewhere,
## see the ideas at
## https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
# Cargar las bibliotecas necesarias
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.3
library(DESeq2)
## Warning: package 'DESeq2' was built under R version 4.3.3
## Loading required package: S4Vectors
## Warning: package 'S4Vectors' was built under R version 4.3.2
## Loading required package: stats4
## Loading required package: BiocGenerics
## Warning: package 'BiocGenerics' was built under R version 4.3.1
## 
## Attaching package: 'BiocGenerics'
## The following objects are masked from 'package:stats':
## 
##     IQR, mad, sd, var, xtabs
## The following objects are masked from 'package:base':
## 
##     anyDuplicated, aperm, append, as.data.frame, basename, cbind,
##     colnames, dirname, do.call, duplicated, eval, evalq, Filter, Find,
##     get, grep, grepl, intersect, is.unsorted, lapply, Map, mapply,
##     match, mget, order, paste, pmax, pmax.int, pmin, pmin.int,
##     Position, rank, rbind, Reduce, rownames, sapply, setdiff, sort,
##     table, tapply, union, unique, unsplit, which.max, which.min
## 
## Attaching package: 'S4Vectors'
## The following object is masked from 'package:utils':
## 
##     findMatches
## The following objects are masked from 'package:base':
## 
##     expand.grid, I, unname
## Loading required package: IRanges
## Warning: package 'IRanges' was built under R version 4.3.1
## 
## Attaching package: 'IRanges'
## The following object is masked from 'package:phyloseq':
## 
##     distance
## The following object is masked from 'package:grDevices':
## 
##     windows
## Loading required package: GenomicRanges
## Warning: package 'GenomicRanges' was built under R version 4.3.1
## Loading required package: GenomeInfoDb
## Warning: package 'GenomeInfoDb' was built under R version 4.3.3
## Loading required package: SummarizedExperiment
## Warning: package 'SummarizedExperiment' was built under R version 4.3.1
## Loading required package: MatrixGenerics
## Warning: package 'MatrixGenerics' was built under R version 4.3.1
## Loading required package: matrixStats
## Warning: package 'matrixStats' was built under R version 4.3.3
## 
## Attaching package: 'MatrixGenerics'
## The following objects are masked from 'package:matrixStats':
## 
##     colAlls, colAnyNAs, colAnys, colAvgsPerRowSet, colCollapse,
##     colCounts, colCummaxs, colCummins, colCumprods, colCumsums,
##     colDiffs, colIQRDiffs, colIQRs, colLogSumExps, colMadDiffs,
##     colMads, colMaxs, colMeans2, colMedians, colMins, colOrderStats,
##     colProds, colQuantiles, colRanges, colRanks, colSdDiffs, colSds,
##     colSums2, colTabulates, colVarDiffs, colVars, colWeightedMads,
##     colWeightedMeans, colWeightedMedians, colWeightedSds,
##     colWeightedVars, rowAlls, rowAnyNAs, rowAnys, rowAvgsPerColSet,
##     rowCollapse, rowCounts, rowCummaxs, rowCummins, rowCumprods,
##     rowCumsums, rowDiffs, rowIQRDiffs, rowIQRs, rowLogSumExps,
##     rowMadDiffs, rowMads, rowMaxs, rowMeans2, rowMedians, rowMins,
##     rowOrderStats, rowProds, rowQuantiles, rowRanges, rowRanks,
##     rowSdDiffs, rowSds, rowSums2, rowTabulates, rowVarDiffs, rowVars,
##     rowWeightedMads, rowWeightedMeans, rowWeightedMedians,
##     rowWeightedSds, rowWeightedVars
## Loading required package: Biobase
## Warning: package 'Biobase' was built under R version 4.3.1
## Welcome to Bioconductor
## 
##     Vignettes contain introductory material; view with
##     'browseVignettes()'. To cite Bioconductor, see
##     'citation("Biobase")', and for packages 'citation("pkgname")'.
## 
## Attaching package: 'Biobase'
## The following object is masked from 'package:MatrixGenerics':
## 
##     rowMedians
## The following objects are masked from 'package:matrixStats':
## 
##     anyMissing, rowMedians
## The following object is masked from 'package:phyloseq':
## 
##     sampleNames
options(repos = c(CRAN = "https://cran.r-project.org"))
# Definir la ruta del directorio
ps <- "C:/Users/HP/Desktop/ps"
# Crear la ruta completa al archivo ps.rds
ps_path <- file.path(ps, "ps.rds")
# Cargar el contenido del archivo ps.rds
datos <- readRDS(ps_path)
# Imprimir el contenido del archivo
print(datos)
## phyloseq-class experiment-level object
## otu_table()   OTU Table:         [ 3020 taxa and 19 samples ]
## sample_data() Sample Data:       [ 19 samples by 9 sample variables ]
## tax_table()   Taxonomy Table:    [ 3020 taxa by 7 taxonomic ranks ]
## phy_tree()    Phylogenetic Tree: [ 3020 tips and 3016 internal nodes ]
chooseCRANmirror(ind = 1)  # Elige un espejo de CRAN de la lista
install.packages("phyloseq", dependencies = TRUE)
## Warning: package 'phyloseq' is in use and will not be installed
options(repos = c(CRAN = "https://cran.r-project.org"))

# Asegurarse de que la columna de grupo está presente en sample_data(datos)
sample_data(datos)$Group <- sample_data(datos)$Estado_de_salud

# 1. Análisis de la diversidad alfa y generación de tests estadísticos
# Calcular métricas de diversidad alfa
diversity_alpha <- estimate_richness(datos, measures = c("Observed", "Shannon", "Simpson"))
diversity_alpha$Group <- sample_data(datos)$Group
options(repos = c(CRAN = "https://cran.r-project.org"))

# Gráfico de la diversidad alfa (Shannon Index)
ggplot(diversity_alpha, aes(x = Group, y = Shannon)) +
  geom_boxplot() +
  geom_jitter(width = 0.2) +
  theme_minimal() +
  labs(title = "Alpha Diversity (Shannon Index)", x = "Group", y = "Shannon Index")

#en la grafica de cajas apreciamos una mayor diversidad entre enfermos y sanos 
# Prueba estadística de la diversidad alfa (Shannon Index)
wilcox.test(Shannon ~ Group, data = diversity_alpha)
## 
##  Wilcoxon rank sum exact test
## 
## data:  Shannon by Group
## W = 13, p-value = 0.007621
## alternative hypothesis: true location shift is not equal to 0
#en los resultados vemos que las diferecnias no son el resultado del azar

install.packages(“phyloseq”)

2. Análisis de la diversidad beta y generación de tests estadísticos

Calcular la matriz de distancia Bray-Curtis

dist_bray <- distance(datos, method = “bray”) ordination <- ordinate(datos, method = “PCoA”, distance = dist_bray) #Gráfico de la diversidad beta




plot_ordination(datos, ordination, color = "Group") +
  geom_point(size = 3) +
  theme_minimal() +
  labs(title = "Beta Diversity (Bray-Curtis PCoA)", x = "PCoA1", y = "PCoA2")
#El resultado significativo del PERMANOVA sugiere que las diferencias entre los grupos son estadísticamente significativas

library(vegan) # Prueba estadística de la diversidad beta adonis2(dist_bray ~ sample_data(datos)\(Group) #No Significativo: El valor p de 0.995 indica que no hay una diferencia significativa entre los grupos (sample_data(datos)\)Group). Esto sugiere que los grupos no tienen una composición significativamente diferente en términos de las distancias de Bray-Curtis calculadas. #Varianza Explicada: El grupo explica solo una pequeña fracción de la variación total (4.75%).



``` r
# 4. Gráficos de barras sobre la taxonomía a nivel phylum
# Normalizar los datos
datos_norm <- transform_sample_counts(datos, function(x) x / sum(x))

# Agregar información taxonómica al nivel de phylum
datos_phylum <- tax_glom(datos_norm, "Phylum")
plot_bar(datos_phylum, x = "Group", fill = "Phylum") +
  geom_bar(stat = "identity") +
  theme_minimal() +
  labs(title = "Taxonomy at Phylum Level", x = "Group", y = "Relative Abundance")

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.