R Documentation
Concise, example-driven R reference. Read the concept, see the code, then practice it in a Coddy journey.
Getting Started
- What Is R?What the R programming language is, where it came from, what it's used for, and how it compares to Python - with a first runnable taste of R code.
- Install RHow to download R from CRAN and install it on Windows, macOS, or Linux, plus RStudio - the IDE nearly everyone uses to write R.
- Run an R ScriptEvery way to run R code: the interactive console, Rscript from the command line, source() from inside R, and the Run and Source commands in RStudio.
- R SyntaxThe core of R syntax: assignment with <-, expressions and auto-printing, function calls with named arguments, and the everything-is-a-vector rule.
- CommentsHow comments work in R: the # symbol, why R has no true multiline comment, the RStudio shortcut for commenting out blocks, and what good comments say.
Variables & Data
- VariablesHow to create variables in R with the <- arrow, when = is required instead, the naming rules, and how to list and remove variables with ls() and rm().
- Data TypesThe atomic data types in R - double, integer, character, logical - plus how typeof() and class() differ, and how conversion and coercion work.
- NumbersWorking with numbers in R: numeric vs integer, the rounding family, sqrt and log, the %% modulo operator, and the special values Inf and NaN.
- StringsEverything you need for text in R: creating strings, joining with paste and paste0, formatting with sprintf, and searching with gsub, grepl, and strsplit.
- Input & OutputHow output works in R - auto-printing, print() vs cat(), message() - and how to read user input with readline() and readLines().
Control Flow
- OperatorsEvery operator you need in R - arithmetic including %% and %/%, vectorized comparisons, the & vs && distinction, and %in% for membership testing.
- If / ElseConditional logic in R - if/else if/else syntax, the brace pitfall that breaks scripts, vectorized ifelse() for whole vectors, and switch() for multi-way choices.
- For LoopsHow for loops work in R - looping over vectors and indices, collecting results without the growing-vector trap, next and break, and when a vectorized call beats a loop.
- While LoopsHow while loops work in R - condition-first looping, repeat with break as R's do-while, next, and the habits that keep you out of infinite loops.
Data Structures
- VectorsVectors are the fundamental unit of R - even a single number is one. How to create them with c(), index them (from 1!), filter them with logical masks, and do math on whole vectors at once.
- ListsLists are R's anything-goes container: mixed types, nested structures, whole data frames. The key skill is knowing when [ returns a smaller list and when [[ returns the element itself.
- MatricesHow to build matrices with matrix(), cbind() and rbind(), index rows and columns, and keep element-wise * separate from true matrix multiplication %*%.
- FactorsFactors are how R stores categorical data: integer codes wearing text labels. How to create them, order them, set the reference level - and dodge the factor-to-numeric trap.
- Data FramesThe data frame is R's spreadsheet: named columns of equal length, each its own type. How to build one, size it up with str() and head(), and get at columns, rows, and cells.
- Missing Values (NA)NA means "unknown" - and it spreads through every calculation it touches. How to detect it with is.na(), skip it with na.rm = TRUE, and drop or replace it deliberately.
Functions & Packages
- FunctionsHow to create a function in R - the function(x) { } syntax, return values, default and named arguments, ... dots, anonymous functions, and how scoping works.
- apply FamilyThe apply family - apply, lapply, sapply, vapply, mapply, and tapply - runs a function over every element of your data. Here's what each one does and when to reach for it.
- PipesWhat %>% means, how the base R native pipe |> works, the rules and placeholders of each, and which one to use in new code.
- PackagesHow R packages work: installing from CRAN with install.packages(), loading with library(), require() vs library(), pkg::fun(), and the packages worth knowing.
- Working DirectoryWhere R looks for files and how to control it: getwd(), setwd(), list.files(), clearing the environment with rm(list = ls()), and why .RData autosaving is a trap.
Data Wrangling
- dplyrWhat dplyr is, how to install it, and how its six core verbs plus the pipe turn messy data-frame code into readable pipelines.
- Filter & SubsetEvery way to keep the rows and columns you want: logical masks with brackets, the subset() one-liner, %in%, NA traps, and dplyr's filter() and select().
- Add Columns (mutate)How to add, transform, and drop data frame columns: df$new <- ..., ifelse() for conditional columns, transform(), and dplyr's mutate() with case_when().
- Rename ColumnsRenaming data frame columns in R: names() and colnames(), rename by position vs by name, setNames(), dplyr rename(), and cleaning messy imported headers.
- SortingHow sorting really works in R: sort() for vectors, why data frames need order()'s index trick, descending and multi-column sorts, and dplyr's arrange().
- Group By & SummarizeEvery way to compute per-group statistics in R: counting with table(), tapply() for one stat per group, aggregate()'s formula interface, and dplyr's group_by() with summarize().
- Merge & JoinsCombining data frames by a shared key: merge() for inner, left, right, and full joins, different key names with by.x/by.y, dplyr's join family, and rbind() for stacking rows.
- Pivot (Reshape)Wide vs long data formats and how to convert between them: tidyr's pivot_longer() and pivot_wider(), the old spread/gather names, and base R's reshape().
Import & Export
- Read CSVHow to import CSV files into R with read.csv() - the arguments that matter, the working-directory trap that causes most failures, and when readr::read_csv is worth it.
- Read ExcelR can't open .xlsx files on its own - the readxl package fills the gap. How to read sheets, ranges, and headers, write Excel back out, and dodge the classic Excel import traps.
- Write CSV & RDSExporting from R: write.csv with row.names = FALSE (always), write.table for other delimiters, and saveRDS for round-trips that don't lose your types.
- DatesR's Date class is a day count wearing a costume. How to parse strings with as.Date, format dates for output, subtract them, build sequences, and when you need POSIXct instead.
Plots & Charts
- plot()How R's plot() function works - plot types, titles and axis labels, colors, point symbols (pch), layering with lines() and abline(), and legends.
- HistogramHow to make a histogram in R with hist() - choosing breaks, styling bars, switching to the density scale, overlaying a normal curve, and the ggplot2 version.
- BoxplotHow to make a box plot in R with boxplot() - reading the box and whiskers, the formula interface for group comparisons, styling, and finding the numbers behind it.
- Scatter PlotHow to make a scatter plot in R - plot two variables with plot(), add a regression line with abline(lm()), smooth with lowess(), and build a pairs() matrix.
- Bar ChartHow to make a bar chart in R with barplot() - from a named vector or a table(), grouped and stacked bars from a matrix, styling, and geom_col vs geom_bar.
- ggplot2How ggplot2 works - the data + aes() + geom mental model, mapping vs setting aesthetics, labs(), facet_wrap(), themes, and saving plots with ggsave().
Statistics
- Descriptive StatisticsHow to summarize data in R: mean(), median(), sd(), var(), summary(), quantile() - what each one computes, the n−1 detail behind sd(), and why R's mode() is a trap.
- CorrelationMeasure how two variables move together with cor(), test whether the relationship is real with cor.test(), and scan many variables at once with a correlation matrix.
- T-TestRun one-sample, two-sample and paired t-tests with t.test(), and - the part that actually matters - read every line of the output: t, df, p-value, confidence interval.
- ANOVACompare the means of three or more groups with aov(), read the ANOVA table cell by cell, and find out which groups actually differ with TukeyHSD().
- Linear RegressionFit a regression with lm(), read every block of summary() - coefficients, standard errors, p-values, R-squared, the F-statistic - and make predictions with predict().
- Logistic RegressionModel yes/no outcomes with glm(family = binomial): read the summary, convert log-odds coefficients into odds ratios with exp(), and get predicted probabilities the right way.
- Confidence IntervalsGet confidence intervals for means, proportions and model coefficients - t.test(), prop.test(), confint() - plus what "95% confident" actually means and how sample size drives the width.
- Random NumbersGenerate random data with rnorm(), runif(), rbinom() and sample(), make it reproducible with set.seed(), and decode R's d/p/q/r naming system for distributions.