R Programming Fundamentals Cheat Sheet
R is a programming language for statistics, analysis, and graphics, with RStudio serving as its integrated development environment (IDE) for writing, executing, and organizing code. Mastering R involves understanding its core components like scripts, the console, projects, and data structures, alongside fundamental programming concepts such as functions, decisions, loops, and data manipulation.
Core Principles
- R is the engine for statistical computing and graphics; RStudio is the workshop where you write and manage your code.
- Projects organize your R workflow, keeping scripts, data, and results together in a dedicated folder.
- Understanding data structures (vectors, matrices, lists, data frames) is crucial for data manipulation.
- Functions encapsulate reusable code, taking arguments and returning results.
- Control flow structures (if/else, for loops) allow R to make decisions and repeat actions.
- Data cleaning and transformation are essential steps before analysis, involving handling missing values (NA) and reshaping data.
- R Markdown and Quarto allow you to combine code, text, and results into reproducible reports.
Action Steps
- Install R and RStudio to begin your R journey.
- Create a new R project to organize your work.
- Write your first R script, save it (e.g., IntroR.R), and execute lines of code using Run or Ctrl+Enter.
- Use the Console to interpret commands and view immediate results.
- Explore data structures like vectors (single type), matrices (2D, single type), lists (heterogeneous), and data frames (tables).
- Define your own functions using `function(arguments) { code; return(result) }`.
- Implement decision-making with `if`/`else` statements and repetitive tasks with `for` loops.
- Handle missing data (NA) using `is.na()`, `na.omit()`, and `na.rm = TRUE` in functions.
- Use `library()` to load packages (e.g., `rio`, `here`, `tidyverse`) for extended functionality.
- Generate reproducible reports using R Markdown (.Rmd) or Quarto (.qmd) files.
Key Terms
- RStudio: An Integrated Development Environment (IDE) that provides a user-friendly interface for writing, executing, and managing R code.
- Script: A file (e.g., .R) containing a sequence of R commands that can be saved and executed.
- Console: The RStudio window where commands are executed immediately and results are displayed.
- Project: A dedicated folder in RStudio that organizes all files related to a specific analysis or task.
- Vector: A fundamental R data structure that holds elements of the same data type (e.g., numeric, character).
- Data Frame: A tabular data structure where columns can have different data types, representing observations and variables.
- Function: A block of reusable code designed to perform a specific task, often taking arguments and returning a value.
- NA: Represents a missing value in R; it is not equivalent to zero or an empty string.
- Pipe Operator (%>%): A function from the `magrittr` package (used heavily in `tidyverse`) that passes the result of the left-hand side as the first argument to the function on the right-hand side, enabling cleaner code.
- R Markdown: A file format (.Rmd) that combines R code, its output, and narrative text into a single document, which can be rendered into various formats (HTML, PDF, Word).
Pro Tips
- Use RStudio Projects to maintain a clear working directory and manage project files effectively.
- Leverage the `here` package to construct file paths relative to your project's root directory, ensuring portability.
- Employ `dplyr` verbs (like `filter`, `mutate`, `select`, `group_by`, `summarise`) for intuitive data manipulation within the tidyverse.
- Understand the difference between assignment (`<-`) and comparison (`==`) operators.
- Utilize comments (`#`) liberally to explain your code, making it easier to understand later.
- The pipe operator (`%>%` or `|>` in newer R versions) chains functions together, improving code readability.
- Always check your data's structure (`str()`) and summary statistics (`summary()`) before analysis.
Pitfalls to Avoid
- Forgetting to load a package with `library()` causes 'could not find function' errors.
- Using `<-` for comparison instead of `==` leads to incorrect logic.
- Ignoring missing values (NA) can result in inaccurate calculations and misleading results.
- Not specifying `na.rm = TRUE` in summary functions (like `mean()`) will yield NA as the result.
- Confusing `[` (subsetting) with `[[` (extracting single element) for lists and vectors.
- Incorrectly specifying file paths can lead to 'file does not exist' errors.
- Not closing R Markdown/Quarto chunks properly can cause parsing errors.
Real World Examples
- Calculating Body Mass Index (BMI): Use R to calculate BMI by defining variables for weight (in kg) and height (in meters), then applying the formula `BMI <- weight / (height^2)`.
- Analyzing patient data from an Ebola outbreak: Importing a dataset (`linelist_raw.xlsx`) using `rio::import()`, cleaning column names with `janitor::clean_names()`, selecting relevant columns with `select()`, and summarizing data using `summary()` or `skim()`.
- Creating a reproducible report on health data: Writing an R Markdown (.Rmd) file that includes code chunks for data analysis (e.g., calculating descriptive statistics) and narrative text explaining the findings, then knitting it into a Word document.
Related cheat sheets
More like this