---
title: "Proteomics Differential Expression"
author: "Swanitha"
date: "2025-09-05"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Load Libraries
```{r libraries}
library(limma)
library(ggplot2)
library(readr)
```
#Load Data
```{r load_data}
load("z_normalized_CORRECTED.RData")
```
#Check range
```{r}
range(z_normalized)
```
## Sample Setup
```{r}
sample_sheet <- data.frame(
    Sample_ID = colnames(z_normalized),
    Fraction = ifelse(grepl("Chrom", colnames(z_normalized)), "Chromatin", "Soluble"),
    Replicate = c(1, 2, 3, 4, 1, 2, 3, 4),
      stringsAsFactors = FALSE
)

sample_sheet$Fraction <- as.factor(sample_sheet$Fraction)

print(sample_sheet)
# Check that Fraction is now a factor
str(sample_sheet$Fraction) 
```


## Differential Expression Analysis

```{r limma_analysis}
# Design matrix
design <- model.matrix(~ Fraction, data = sample_sheet)
print(design)

# Limma analysis
fit <- lmFit(z_normalized, design)
fit <- eBayes(fit)

# Results summary
summary(decideTests(fit))
```

## Extract Results

```{r results}
# Extract all results
results <- topTable(fit, coef = 2, number = Inf)

# Basic statistics
summary(results$adj.P.Val < 0.05)
summary(results$logFC)
```
```{r}
# Top 20 results
head(results, 20)

#Bottom 20 results
tail(results, 20)
```
## Classify Results

```{r classification}
# Significant proteins
upregulated <- results[results$logFC > 0 & results$adj.P.Val < 0.05, ]
downregulated <- results[results$logFC < 0 & results$adj.P.Val < 0.05, ]

# Count significant proteins
sig_up <- nrow(upregulated)
sig_down <- nrow(downregulated)

print(paste("Upregulated proteins:", sig_up))
print(paste("Downregulated proteins:", sig_down))
```

## Histone Analysis

```{r histones}
# Extract histone proteins
histones <- results[grepl("_H1|_H2A|_H2B|_H3|_H4", rownames(results)), ]
print(histones)
```

## Basic Visualization

```{r volcano_plot}
plot(results$logFC, -log10(results$P.Value), 
     xlab = "log2(Fold Change)", ylab = "-log10(P-value)",
     main = "Volcano Plot: Soluble vs Chromatin",
     col = "black", pch = 16)

# Add significance threshold line
abline(h = -log10(0.05), col = "red", lty = 2)
abline(v = 0, col = "red", lty = 2)

# Identify and highlight significant points
sig <- subset(results, P.Value< 0.05);
points(sig$logFC, -log10(sig$P.Value), col = "blue", pch = 16)

```

