2: R Data Structures & Biological Variables
Chapter 2: R Data Structures & Biological Variables
Genomics datasets encompass diverse data types: raw read counts (integers), variant allele frequencies (floats), chromosomal coordinates (vectors), and clinical tumor stages (ordered factors). Understanding how R stores and manipulates these primitives prevents critical statistical errors.
1. Atomic Vectors in Genomics
Vectors are the fundamental one-dimensional contiguous array in R:
gene_symbols <- c("TP53", "EGFR", "BRCA1", "MYC", "KRAS", "PTEN")
log2_fc <- c(2.45, -1.82, 3.12, -0.45, 1.95, -2.10)
p_values <- c(1.2e-6, 4.5e-4, 8.9e-9, 0.42, 3.1e-5, 2.8e-5)
# Logical vector subsetting (FDR < 0.001 & |log2FC| >= 1.5)
is_sig <- (p_values < 0.001) & (abs(log2_fc) >= 1.5)
cat("Significant Driver Genes:", paste(gene_symbols[is_sig], collapse=", "), "\n")2. Factors: Crucial for RNA-Seq Experimental Design
Factors represent categorical data with defined levels. In differential expression packages like DESeq2, the first level is automatically treated as the baseline reference. Specifying levels explicitly is mandatory:
# Sample conditions
raw_conditions <- c("Control", "Treated", "Control", "Treated", "Control", "Treated")
# Explicitly setting Control as reference level 1
condition_factor <- factor(raw_conditions, levels = c("Control", "Treated"))
print(levels(condition_factor))
# Ordered factors for clinical staging
tumor_stage <- factor(c("Stage_I", "Stage_IV", "Stage_II", "Stage_III"),
levels = c("Stage_I", "Stage_II", "Stage_III", "Stage_IV"),
ordered = TRUE)
print(table(tumor_stage))3. Gene Expression Count Matrices
Matrices store two-dimensional numerical data where all elements share the same type (integer counts):
counts_matrix <- matrix(
c(120, 850, 45, 3200, 140, 890, 52, 3100),
nrow = 4, ncol = 2,
dimnames = list(c("TP53", "EGFR", "BRCA1", "MYC"), c("Sample_1", "Sample_2"))
)
print(counts_matrix)
# Computing sequencing library depths
cat("Library Depths (Reads per Sample):\n")
print(colSums(counts_matrix))4. Data Frames: Integrating Clinical Metadata
Data frames hold columns of mixed types (numeric, factor, character), making them ideal for sample phenotypic metadata (colData):
col_data <- data.frame(
SampleID = c("S1", "S2", "S3", "S4"),
Condition = factor(c("Control", "Control", "Treated", "Treated"), levels = c("Control", "Treated")),
Age = c(54, 62, 47, 71),
Batch = factor(c("Batch_1", "Batch_2", "Batch_1", "Batch_2")),
row.names = c("S1", "S2", "S3", "S4")
)
print(col_data)