Lesson · 40 min · Free
Data Structures and Functions in R
Data Structures and Functions in R Data Structures and Functions in R Welcome to the "Computational Biomedicine: From Command Line to Single-Cell" course! In this lesson, we'll delve into the fundamental building blocks
Data Structures and Functions in R
Welcome to the "Computational Biomedicine: From Command Line to Single-Cell" course! In this lesson, we'll delve into the fundamental building blocks of data manipulation and analysis in R: data structures and functions. A strong grasp of these concepts is crucial for effectively handling biomedical datasets, whether you're working with patient cohorts, gene expression profiles, or single-cell sequencing data. R offers a variety of data structures, each optimized for different types of data and operations. Understanding which structure to use for a given task can significantly impact the efficiency and clarity of your code. We'll cover the most commonly used structures, including vectors, matrices, data frames, and lists. Beyond just storing data, we'll also explore how to write and utilize functions, which are essential for organizing your code, promoting reusability, and performing complex analyses systematically.
Essential R Data Structures
Let's begin by examining the core data structures you'll encounter and utilize frequently in R. Each structure has distinct characteristics that make it suitable for particular types of data organization.
Vectors
Vectors are the most basic data structure in R. They are one-dimensional arrays that can hold elements of the same data type (e.g., all numbers, all characters, or all logical values). You can create vectors using the c() function (short for "combine"). # Numeric vector for patient ages patient_ages
Matrices
Matrices are two-dimensional arrays where all elements must be of the same data type. They are particularly useful for numerical operations, such as those encountered in linear algebra or when representing gene expression counts for a small set of genes across samples. You can create a matrix using the matrix() function, specifying the data, number of rows, and number of columns. # Gene expression matrix (rows are genes, columns are samples) gene_expression_data
Data Frames
Data frames are perhaps the most commonly used data structure in R for biomedical data. They are similar to spreadsheets or SQL tables, where each column can be a different data type (e.g., one column for patient IDs (character), another for age (numeric), and another for disease status (factor/character)). Each row typically represents an observation (e.g., a patient, a sample). You can create data frames using the data.frame() function. # Creating a data frame for patient clinical data patient_data
Lists
Lists are the most flexible data structure in R. They can contain elements of different data types and even other data structures (e.g., a list can contain vectors, matrices, data frames, or even other lists). This makes them incredibly powerful for storing heterogeneous information, such as the results of a complex analysis pipeline where you might have different outputs (e.g., a data frame of statistics, a vector of significant genes, and a plot object). # Creating a list to store results from a gene enrichment analysis enrichment_results
Functions in R
Functions are blocks of organized, reusable code that perform a single, related action. They are fundamental to writing efficient, readable, and maintainable R code. You'll use many built-in R functions, but you'll also frequently write your own to encapsulate specific analytical steps or data transformations.
Defining a Function
A function in R is defined using the function() keyword, followed by its arguments in parentheses, and the body of the function enclosed in curly braces {} . The last expression evaluated in the function is returned as the result, or you can explicitly use the return() function. # Function to calculate the mean expression of a gene calculate_mean_expression
Functions with Multiple Arguments and Default Values
Functions can take multiple arguments, and you can assign default values to arguments. This makes functions more flexible, allowing them to be called with fewer arguments if the default values are suitable. # Function to perform basic normalization (e.g., log2 transformation) normalize_expression
Key Takeaways
Vectors: One-dimensional, homogeneous data (e.g., a list of patient ages). Matrices: Two-dimensional, homogeneous data (e.g., gene expression values for multiple genes and samples). Data Frames: Two-dimensional, heterogeneous data, similar to a spreadsheet, ideal for clinical or experimental metadata. Lists: Highly flexible, can store heterogeneous data types and structures, useful for complex analysis outputs. Functions: Reusable blocks of code for specific tasks, improving code organization and efficiency.
Practice Exercise
Create a data frame named drug_trial_data with three columns: Patient_ID (character), Drug_Dose_mg (numeric), and Response_Score (numeric, ranging from 1 to 10). Populate it with at least 5 rows of hypothetical data. Then, write a function called calculate_average_response that takes this data frame as input and returns the average Response_Score for all patients. Finally, call your function and print the result.
Watch the full lesson — free
This topic is part of Computational Biomedicine: From Command Line to Single-Cell, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →