--- title: "Comparing Two Groups with prolfqua" author: "Witold E. Wolski" date: "`r Sys.Date()`" output: BiocStyle::html_document vignette: > %\VignetteIndexEntry{3. Comparing Two Groups with prolfqua} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console bibliography: - prolfqua.bib --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) library(dplyr) ``` # Purpose This vignette demonstrates how two conditions, e.g., treatment vs. control, can be compared and the differences statistically tested. We use simulated protein abundances of an LFQ experiment with two treatment groups (`A`, `B`) and a control group (`Ctrl`). After first examining the data using QC plots and then normalizing the data, we compare each treatment group with the control. The output of the comparison is the difference in the mean intensities for quantified proteins (log2 fold-change) in each group, along with statistical parameters such as degrees of freedom, standard errors, p-value and the FDR. # Simulated protein abundances ```{r createConfig} library(prolfqua) ``` `sim_lfq_data_protein_config()` simulates protein abundances in long format, one row per protein and sample, and returns them together with a matching `AnalysisConfiguration`. To read your own data, see the article [Importing your data](https://fgcz.github.io/prolfqua/articles/CreatingConfigurations.html). ```{r LoadDataAndConfigure} xx <- prolfqua::sim_lfq_data_protein_config(Nprot = 100, weight_missing = 0.5) xx ``` Create the `LFQData` class instance and remove zero or very small intensities, which most quantification software reports for missing values. ```{r removeSmallIntensities} lfqdata <- prolfqua::LFQData$new(xx$data, xx$config) lfqdata$remove_small_intensities() lfqdata$factors() ``` You can always convert the data into wide format. ```{r showWide, eval = TRUE} lfqdata$data_wide()$data[1:3,1:7] ``` ## Visualization of not normalized data After this first setting up of the analysis we show now how to normalize the proteins and the effect of normalization. Furthermore we use some functions to visualize the missing values in our data. ```{r getPlotter} lfqplotter <- lfqdata$get_Plotter() density_nn <- lfqplotter$intensity_distribution_density() ``` ### Visualization of missing data ```{r makeMissingHeatmap, fig.cap="Heatmap of missing protein intensities, black - missing, white - present"} lfqplotter$na_heatmap() ``` ```{r missignessPerGroup, fig.cap="# of proteins with 0,1,...N missing values"} lfqdata$get_Summariser()$plot_missingness_per_group() ``` ```{r missignessHistogram, fig.cap="Intensity distribution of proteins depending on # of missing values"} lfqplotter$missigness_histogram() ``` ### Computing standard deviations, mean and CV. Other important statistics such as coefficient of variation, means and standard deviations can be easily calculated using the `get_Stats` function and visualized with a violin plot. ```{r PlotCVDistributions, fig.cap="Violin plots of CVs in the different groups and among all groups"} stats <- lfqdata$get_Stats() stats$violin() prolfqua::table_facade( stats$stats_quantiles()$wide, paste0("quantile of ",stats$stat )) ``` ```{r plotCVsplitbyMedianIntensity, fig.cap="Distribution of CV's for top 50% and bottom 50% proteins by intensity."} stats$density_median() ``` ## Normalize protein intensities and show diagnostic plots We normalize the data by $\log_2$ transforming and then $z-scaling$. ```{r normalizedata} lt <- lfqdata$get_Transformer() transformed <- lt$log2()$robscale()$lfq transformed$is_transformed() ``` ```{r genplotNorm, fig.cap="Normalized intensities."} pl <- transformed$get_Plotter() density_norm <- pl$intensity_distribution_density() ``` ```{r showIntensityDistributions, fig.cap="Distribution of intensities before and after normalization."} gridExtra::grid.arrange(density_nn, density_norm) ``` ```{r plotScatterMatrix, fig.cap = "Scatterplot matrix"} pl$pairs_smooth() ``` ```{r createHeatmap} p <- pl$heatmap_cor() ``` ```{r plotHeatmap, fig.cap="Heatmap, Rows - proteins, Columns - samples", fig.align=5, fig.height=5} p ``` # Fit the model and compute contrasts We compare each treatment group with the control. `build_contrast_analysis()` fits one model per protein and computes the contrasts in one call. We use the method `lm_impute`: a linear model per protein, with the protein variances moderated by the empirical Bayes method so that proteins with few observations borrow strength from all proteins. Proteins without observations in one group are refitted with the missing values set to the limit of detection (LOD). The article [Filling the gaps](https://fgcz.github.io/prolfqua/articles/ModelBasedImputation.html) uses these models to complete the data for heatmaps and PCA. The vignette [All modelling methods at a glance](ModellingMethods.html) lists the other methods. ```{r computeContrasts} contr_spec <- c( "AvsC" = "group_A - group_Ctrl", "BvsC" = "group_B - group_Ctrl" ) fa <- build_contrast_analysis(transformed, "~ group_", contr_spec, method = "lm_impute") contrdf <- fa$get_contrasts() ``` The column `estimate_type` tells how each estimate was obtained: `observed` from the measured intensities, `lod_imputed` from the refit at the LOD. ```{r estimateType} dplyr::count(contrdf, contrast, estimate_type) ``` ```{r plotVolcanos, fig.cap="Volcano plots of the two contrasts."} plotter <- fa$get_Plotter() plotter$volcano()$FDR ``` ```{r showMAplot, fig.cap="MA plot showing the dependency of mean abundance with respect to the difference"} plotter$ma_plot() ``` The proteins with FDR < 0.1 in at least one contrast: ```{r createSigHeatmap} sig <- dplyr::filter(contrdf, FDR < 0.1) signif <- transformed$get_copy() signif$set_data(signif$data_long() |> dplyr::filter(protein_Id %in% sig$protein_Id)) hmSig <- signif$get_Plotter()$heatmap() ``` ```{r showSigHeatmap, fig.cap="Heatmap of the proteins with FDR < 0.1 in at least one contrast"} hmSig ``` ```{r checkProteinsInOutput} myProteinIDS <- head(unique(contrdf$protein_Id), 3) dplyr::filter(contrdf, protein_Id %in% myProteinIDS) ``` Protein and contrast pairs that `lm_impute` could not estimate, if any: ```{r missingContrasts} fa$get_missing() ``` # Gene Set Enrichment Analysis (GSEA) After computing contrasts, proteins can be ranked by log2 fold change or t-statistic and subjected to gene set enrichment analysis. The typical workflow is: 1. Extract UniProt IDs from the contrast results using `prolfqua::get_uniprot_id_from_fasta_header()` 2. Map UniProt IDs to Entrez Gene IDs using `AnnotationDbi::mapIds()` with a species-specific annotation package 3. Create a named ranked list (statistic values named by gene IDs) 4. Run GSEA using `clusterProfiler::gseGO()` or `clusterProfiler::gseKEGG()` For details see: - [clusterProfiler book](https://yulab-smu.top/biomedical-knowledge-mining-book/) -- comprehensive guide to enrichment analysis in R - [clusterProfiler Bioconductor page](https://bioconductor.org/packages/clusterProfiler/) - [AnnotationDbi](https://bioconductor.org/packages/AnnotationDbi/) -- for mapping between gene identifier types The `prolfqua` package is described in [@Wolski2023prolfqua]. # Session Info ```{r session_info} sessionInfo() ``` # References