R Programming Tutorial
Learn R Programming step by step: 39 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is R? Learn what R is, what it is used for, how it differs from Python and Excel, and how an R analysis flows from raw data to results you can share.
- Install R and RStudio Install R and the RStudio IDE on Windows, macOS or Linux, tour the four panes, and run your first commands in the console and in a script file.
- R Basics: Values, Variables and Operators Learn the building blocks of R code: arithmetic and comparison operators, assigning variables, naming rules, calling functions, comments and printing output.
- R Packages: Install, Load and Use Learn what R packages are, how to install them from CRAN with install.packages(), load them with library(), call functions with ::, and manage updates.
- Getting Help and Working Efficiently in R Learn how to read R help pages, search documentation, understand error messages and warnings, ask good questions, and build habits for clean, reproducible scripts.
Data Types and Structures
- Vectors in R Master R vectors, the core data structure. Create them with c(), seq() and rep(), index with positions, names and conditions, and use vectorized math and recycling.
- Data Types and Coercion in R Understand R's basic data types, how to check and convert them with class() and as.numeric(), how automatic coercion works, and how NA, NULL, NaN and Inf differ.
- Factors: Categorical Data in R Learn R factors for categorical data. Create them, control levels and order, count categories with table(), bin numbers with cut(), and avoid the as.numeric trap.
- Matrices and Arrays in R Create and use R matrices and arrays. Learn matrix(), dim(), indexing rows and columns, cbind and rbind, element-wise versus matrix multiplication, and solve().
- Lists in R Learn R lists, the flexible container for mixed types. Create named lists, use $, [ ] and [[ ]] correctly, add and remove items, nest lists and flatten with unlist().
Control Flow and Functions
- Conditionals: if, else, ifelse and switch Make decisions in R code with if, else if and else, the vectorized ifelse(), switch() and case_when(). Learn && versus &, any(), all() and common conditional mistakes.
- Loops in R: for, while and repeat Learn R loops: for, while and repeat with break and next, why seq_along() beats 1:length(x), how to preallocate results, and when vectorized code replaces a loop.
- Writing Functions in R Write your own R functions. Learn function(), default and named arguments, return values, validating input with stop(), scope, closures, anonymous functions and the pipe.
- The apply Family: lapply, sapply, vapply, apply and Map Replace loops with the R apply family. Learn lapply, sapply, vapply, apply, tapply and mapply, plus Map, Filter and Reduce, and know which one returns what.
- Errors, Warnings and Debugging in R Handle problems in R code. Raise errors with stop(), warn with warning(), catch them with tryCatch() and try(), clean up with finally, and debug with traceback() and browser().
Data Frames and Data Wrangling
- Data Frames in R Learn R data frames, the standard table for analysis. Build them with data.frame(), inspect with str() and summary(), add columns and rows, sort with order() and meet tibbles.
- Reading and Writing Data in R Import and export data in R. Use read.csv() and write.csv(), readr, readxl and jsonlite, handle missing-value codes and encodings, and save objects with saveRDS().
- Subsetting Data Frames: Rows, Columns and Filters Select rows and columns from R data frames with df[rows, cols], $, [[ ]], logical filters, %in%, subset(), which() and na.omit(), and avoid the NA filtering trap.
- dplyr Basics: filter, select, mutate, summarise Wrangle data with dplyr. Learn filter(), select(), arrange(), mutate(), group_by(), summarise() and count(), chain them with the pipe, and compare them with base R.
- Tidying, Joining and Missing Values Reshape data with tidyr pivot_longer() and pivot_wider(), combine tables with dplyr joins, stack with bind_rows(), and deal with missing values using drop_na(), replace_na() and coalesce().
Strings, Dates and Regular Expressions
- R Strings: Create, Combine, Format and Slice Text Learn how to work with text in R: creating strings, paste and paste0, nchar, substr, strsplit, case changes, sprintf and format, raw strings and common mistakes.
- Regular Expressions in R: grepl, sub, gsub and regmatches Search, test, replace and extract text with regular expressions in R: grepl, grep, sub, gsub, regexpr, gregexpr, regmatches, character classes, groups and lookaheads.
- Dates and Times in R: Date, POSIXct, format and difftime Work with dates and times in base R: as.Date, format codes, date arithmetic, seq, difftime, POSIXct and POSIXlt, time zones, and the traps of month-end dates.
- stringr and lubridate: Tidy Text and Date Handling in R Use stringr and lubridate from the tidyverse: str_detect, str_replace_all, str_extract, ymd, dmy, periods versus durations, floor_date, time zones and month-end rules.
Visualization
- Base R Graphics: plot, hist, barplot, boxplot and par Draw charts with base R: plot, lines, points, hist, barplot, boxplot, pie, colors, legends, multi-panel layouts with par, and saving figures to PNG or PDF.
- ggplot2 Basics: The Grammar of Graphics in R Learn ggplot2 from scratch: the grammar of graphics, data and aes, geom_point, geom_line, geom_col, histograms, box plots, smoothers, color mapping versus setting, and layers.
- Customizing ggplot2: Facets, Scales, Labels and Themes Make ggplot2 charts clear and professional: facet_wrap and facet_grid, scales and colors, labs, themes, axis formatting, annotations, flipping bars, combining plots and saving.
- Choosing the Right Chart in R: Distributions to Time Series Pick the right chart for your question: distributions, comparisons, relationships, change over time and parts of a whole, with ggplot2 recipes and honest-design rules.
Statistics and Modeling
- Descriptive Statistics in R: mean, sd, quantile, summary, cor Summarize data in R: mean, median, mode, variance, standard deviation, range, quantiles, IQR, summary(), table(), tapply(), aggregate(), correlation, z-scores and missing values.
- Probability Distributions in R: dnorm, pnorm, qnorm, rnorm Master R's distribution functions: the d, p, q and r prefixes for normal, binomial, Poisson, uniform, exponential, t and chi-squared, plus sample(), set.seed() and simulation.
- Hypothesis Tests in R: t.test, chisq.test, cor.test and More Run and interpret hypothesis tests in R: t.test (one, two-sample, paired), chisq.test, prop.test, cor.test, shapiro.test, wilcox.test, aov, p.adjust and power calculations.
- Linear and Logistic Regression in R: lm, glm, predict Fit and interpret regression models in R: lm(), summary(), coefficients, confidence intervals, predict(), residual diagnostics, multiple regression, glm() logistic regression and odds ratios.
Advanced R
- Functional Programming in R: apply, Map, Reduce, Closures, purrr Write cleaner R with functional programming: first-class functions, anonymous functions, lapply, sapply, vapply, Map, Filter, Reduce, closures, function factories and purrr.
- Object-Oriented Programming in R: S3, S4, Reference Classes and R6 Understand R's object systems: S3 classes and generics (UseMethod, NextMethod), S4 classes with validity, reference classes, R6 with private fields, and when to choose each.
- Error Handling and Debugging in R: tryCatch, stop, browser Handle problems in R code: messages, warnings and errors, stop(), tryCatch(), finally, custom conditions, on.exit(), stopifnot(), and debugging with traceback(), browser() and debug().
- R Performance and Packages: Vectorization, Profiling, Your First Package Speed up R code with vectorization, preallocation and profiling (system.time, bench, profvis), handle big data, run in parallel, then package your work with usethis, roxygen2 and testthat.
Projects and Practice
- R Project: Do Manual Cars Really Get Better Mileage? (mtcars) A complete R analysis from question to conclusion on the mtcars data: inspect, clean, summarize, visualize, test, model, and discover how weight confounds the transmission effect.
- R Project: Simulation, Monte Carlo and the Bootstrap Learn by simulating in R: estimate pi, solve the birthday problem, build bootstrap confidence intervals, run a permutation test and check what a 95% interval really means.
- R Practice Exercises with Solutions: Strings to Regression Fifteen graded R exercises with full solutions: strings, regular expressions, dates, statistics, distributions, tests, regression, functional programming, S3, error handling and ggplot2.