What Is R?
R is a programming language used for statistical analysis, data processing, and data visualization. It helps researchers organize large datasets, perform calculations, and create graphs to understand patterns in data.
In bioinformatics, R is used to analyze gene expression, biological experiments, and sequencing data. It provides functions and packages that make it easier to work with biological information.
What Is Bioconductor?
Bioconductor is an open-source project that provides R packages for analyzing biological data. These packages are designed for tasks such as gene expression analysis, RNA sequencing, genomic data processing, and statistical analysis.
R provides the programming environment, while Bioconductor provides specialized tools for biological research. Together, they help researchers analyze biological datasets and visualize their results.
Installing R and RStudio
Before working with R and Bioconductor, you need to install R and an environment for writing and running R code.
- Download and install R from the CRAN website.
- Download and install RStudio from the Posit website.
- Open RStudio and run the following code to check your R version.
R.version.string
R 4.1 or newer is required for the native pipe operator |> used in this tutorial.
1. R Basics
R provides variables, vectors, data frames, and functions to store and process data. These features are useful when working with biological measurements and gene expression values.
Variables and Vectors in R
A variable stores a value that can be used later in a program. A vector stores multiple values of the same basic data type.
# Store a single value
x <- 5# Create a vector
expr_values <- c(2.3, 5.1, 3.8, 7.2)# Assign names to values
names(expr_values) <- c("GeneA", "GeneB", "GeneC", "GeneD")# Display the values
expr_values# Calculate the average
mean(expr_values)# Select values greater than 4
expr_values[expr_values > 4]
Explanation
In this example, <- assigns a value to a variable, c() combines values into a vector, and mean() calculates their average.
Data Frames in R
A data frame stores data in rows and columns, similar to a spreadsheet. Each column can contain a different type of information, such as sample names, experimental groups, or gene expression values.
samples <- data.frame(
sample = c("S1", "S2", "S3", "S4"),
group = c("Control", "Control", "Treated", "Treated"),
expression = c(2.3, 2.9, 6.1, 7.2)
)samples
samples$expression
samples[3, ]
nrow(samples)
Creating Functions in R
A function is a reusable block of code that performs a specific task. Functions help avoid repeating the same calculations. For example, the following function calculates the log2 fold change between treated and control expression values.
log2_fold_change <- function(treated, control) {
log2(treated / control)
}log2_fold_change(treated = 6.1, control = 2.3)
Reading a CSV File in R
Biological datasets are often stored in CSV files. R provides the read.csv() function to import these files into a data frame.
my_data <- read.csv("my_data.csv")
head(my_data)
summary(my_data)
Make sure the CSV file is available in your working directory or provide its correct file path.
2. Tidyverse for Biological Data Analysis
The tidyverse is a collection of R packages used to import, clean, transform, and analyze data. It includes tools such as dplyr and ggplot2 that make data manipulation and visualization easier. The native pipe operator |> passes the result of one operation to the next, making data processing steps easier to read.
Installing Tidyverse
install.packages("tidyverse")
library(tidyverse)
Run install.packages() when installing the package for the first time. Use library() whenever you start a new R session and need the package.
Creating a Gene Expression Dataset
genes <- tibble(
gene = c("TP53", "BRCA1", "MYC", "EGFR", "GAPDH", "ACTB"),
control = c(5.2, 3.1, 8.4, 4.0, 10.1, 9.8),
treated = c(9.9, 2.8, 15.0, 4.2, 10.3, 9.7)
)
A tibble is a modern version of a data frame that provides convenient printing and works well with tidyverse functions.
Important Tidyverse Functions
1. mutate()
The mutate() function creates a new column or modifies an existing column.
genes <- genes |>
mutate(log2FC = log2(treated / control))genes
Here, log2FC stores the log2 fold change for each gene.
2. filter()
The filter() function selects rows that meet a specified condition.
genes |>
filter(log2FC > 0.5)
This example selects genes whose treated-to-control expression ratio corresponds to a log2 fold change greater than 0.5.
3. select()
The select() function chooses specific columns from a dataset.
genes |>
select(gene, log2FC)
This returns only the gene names and their log2 fold changes.
4. arrange()
The arrange() function sorts rows according to one or more columns.
genes |>
arrange(desc(log2FC))
The desc() function sorts the values from highest to lowest.
5. group_by() and summarise()
The group_by() function groups rows based on a column, while summarise() calculates statistics for each group.
group_table <- tibble(
group = c("Control", "Control", "Treated", "Treated"),
value = c(2.3, 2.9, 6.1, 7.2)
)group_table |>
group_by(group) |>
summarise(
average = mean(value),
n = n()
)
These functions help compare groups and summarize experimental measurements.
3. Data Visualization Using ggplot2
ggplot2 is an R package for creating graphs and charts. It uses a layered approach in which data, aesthetic mappings, and geometric objects are combined to produce a visualization.
It is useful in bioinformatics for comparing gene expression, examining sample distributions, and presenting statistical results.
Creating a Scatter Plot
A scatter plot displays the relationship between two numerical variables. In gene expression analysis, it can compare expression values under control and treated conditions.
ggplot(genes, aes(x = control, y = treated, label = gene)) +
geom_point(size = 3, colour = "steelblue") +
geom_text(vjust = -0.8) +
labs(
title = "Gene Expression: Control vs Treated",
x = "Control Expression",
y = "Treated Expression"
) +
theme_minimal()
Each point represents a gene. The horizontal axis shows its control expression, while the vertical axis shows its treated expression.
Creating a Box Plot
A box plot summarizes the distribution of numerical values. It displays the median, quartiles, and potential outliers, making it useful for comparing measurements across groups.
plant <- tibble(
group = rep(c("Control", "Treated"), each = 6),
height = c(
12, 14, 13, 15, 12, 14,
18, 20, 19, 22, 21, 19
)
)ggplot(plant, aes(x = group, y = height, fill = group)) +
geom_boxplot(alpha = 0.7) +
geom_jitter(width = 0.1) +
labs(
title = "Plant Height by Treatment Group",
x = "Group",
y = "Height (cm)"
) +
theme_classic()
The box plot compares the distributions of plant heights in the two groups. The jittered points show individual observations.
Saving a Graph in R
The ggsave() function saves the most recently displayed ggplot graph to a file.
ggsave(
"plant_height.png",
width = 6,
height = 4,
dpi = 300
)
The graph is saved as a PNG file with a resolution of 300 dots per inch.
Conclusion
R is a useful programming language for statistical analysis, data processing, and data visualization. In bioinformatics, it helps researchers organize biological data, analyze gene expression, and identify patterns in experimental results.
Tidyverse makes data manipulation easier, while ggplot2 helps create graphs for comparing and understanding biological measurements. These tools provide a foundation for working with larger biological datasets.