R Tutorial
The language of statistics, data analysis and charts.
Getting started4 lessons
Basics21 lessons
- 5R VariablesAssign with <-.
- 6R Data TypesBasic types: numeric (double), integer (5L), character, logical (TRUE/FALSE), complex and .
- 7R NumbersR has numeric and integer types.
- 8R StringsStrings use quotes.
- 9R LogicalsLogical values are TRUE and FALSE.
- 10R OperatorsArithmetic: + - * / ^ %% %/%.
- 11R Math FunctionsR includes exp, log, sin, cos, abs, floor, ceiling, round, cumsum and prod.
- 12Sequences and Sortingseq makes sequences, rep repeats, sort orders a vector, order gives positions and rev reve.
- 13R Output and Formattingcat prints text without quotes, print shows R values, sprintf formats numbers and format c.
- 14AssignmentUse <- to assign.
- 15Basic Typesnumeric, integer, character, logical, complex and NULL.
- 16VectorsA vector is the basic R structure.
- 17Vector ArithmeticOperations work on whole vectors element by element.
- 18Sequences: makes ranges, seq() gives steps and rep() repeats values.
- 19Indexing VectorsUse positive indexes, negatives to drop, logical vectors and names.
- 20NA, NULL and Missing ValuesNA marks missing data and NULL is nothing.
- 21Stringspaste joins, nchar counts, substr slices and toupper changes case.
- 22Searching and Replacing Textgrepl tests, sub and gsub replace, strsplit splits and regmatches extracts.
- 23Math Functionssqrt, abs, round, floor, ceiling, exp, log and trig work on vectors.
- 24FactorsA factor stores categories as levels.
- 25Datesas.Date converts text to dates.
Control flow16 lessons
- 26R If Elseif runs code when a condition is TRUE.
- 27R Switchswitch picks by name or number.
- 28R For and While Loopsfor iterates over a vector, while repeats on a condition and repeat loops until break.
- 29R FunctionsCreate a function with function().
- 30R Scope and ClosuresVariables inside a function are local.
- 31R Repeat and Breakrepeat loops forever until break.
- 32if and elseif takes a single TRUE or FALSE.
- 33for and while Loopsfor walks a vector and while repeats on a condition.
- 34repeat and switchrepeat loops until break.
- 35Vectorising Instead of LoopingVector operations are faster and shorter than loops.
- 36FunctionsCreate with function().
- 37Returning Several ValuesReturn a list to give back several values.
- 38Scope and ClosuresFunctions see variables from where they were defined.
- 39The Pipe Operator|> passes the left side as the first argument of the function on the right.
- 40Errors and tryCatchtryCatch handles errors and warnings.
- 41RecursionA function may call itself with a base case.
Data structures18 lessons
- 42R VectorsA vector holds values of one type.
- 43R ListsA list can hold elements of different types and names.
- 44R MatricesA matrix is a 2D structure of one type.
- 45R Arrays and FactorsAn array has more than two dimensions.
- 46R Data FramesA data frame is a table of columns, each a vector.
- 47Apply Functionsapply, sapply, lapply and vapply run a function over elements without writing loops.
- 48Set Operationsunion, intersect, setdiff and unique treat vectors as sets.
- 49ListsA list holds items of different types.
- 50MatricesA matrix is a two dimensional vector of one type.
- 51Arrays and applyapply runs a function over rows or columns.
- 52Data FramesA data frame is a table where each column is a vector.
- 53Subsetting Data FramesUse rows, columns and conditions with [ , ] or subset().
- 54Adding and Changing ColumnsAssign to a new name to add a column.
- 55Summaries of Data Framessummary(), head(), str() and table() describe a data frame quickly.
- 56The apply Familylapply and sapply run a function over a list or vector.
- 57seq_along and Loop Helpersseq_along and seq_len make safe loop indexes.
- 58Sorting and Orderingsort sorts values and order gives the positions.
- 59Set Operationsunion, intersect, setdiff and %in% work on vectors.
Data work14 lessons
- 60Importing Dataread.csv reads a CSV file into a data frame and write.csv saves one.
- 61Cleaning DataMissing values are NA.
- 62Data Wrangling with dplyrdplyr offers verbs: filter, select, mutate, arrange, group_by and summarise, chained with .
- 63Dates and Regular Expressionsas.Date converts text to dates and format prints them.
- 64Reading and Writing CSVread.csv reads a file and write.csv writes one.
- 65Merging Tablesmerge joins two data frames on a shared column like a SQL join.
- 66aggregate and by-group Summariesaggregate summarises a column by groups.
- 67Sorting a Data FrameUse order() to sort rows by one or more columns.
- 68Frequency Tablestable counts values and prop.table gives proportions.
- 69Binning with cutcut puts numbers into labelled intervals.
- 70Applying Functions to Columnssapply over a data frame runs a function on each column.
- 71Duplicates and Unique Rowsduplicated and unique find repeated values or rows.
- 72Handling Missing Datacomplete.cases, na.omit and replacement handle NA values.
- 73Formatting Outputformat, formatC and sprintf control number output.
Statistics13 lessons
- 74Descriptive Statisticsmean, median, sd, var, min, max, quantile and summary describe a dataset.
- 75Probability DistributionsFunctions starting with d, p, q and r give density, cumulative probability, quantile and r.
- 76Correlation and Linear Regressioncor measures how two variables move together.
- 77Hypothesis Testst.test compares means, chisq.test tests counts and cor.test tests correlation.
- 78Descriptive Statisticsmean, median, var, sd, range, quantile and summary describe numbers.
- 79Correlationcor measures how two vectors move together from -1 to 1.
- 80Linear Regressionlm fits a line.
- 81Probability Distributionsd, p, q and r prefixes give density, probability, quantile and random values.
- 82Sampling and Seedssample picks random items.
- 83Hypothesis Testst.test compares means and returns a p value.
- 84Scaling and Cumulative Valuesscale standardises, cumsum and cumprod accumulate.
- 85Matrix StatisticsRow and column summaries describe a numeric matrix.
- 86Finding OutliersThe boxplot rule flags values far outside the quartiles.
Visualisation14 lessons
- 87Base R Plotsplot, hist, barplot, boxplot and lines draw charts.
- 88ggplot2ggplot2 builds charts by layers: data, aesthetics with aes(), then geoms such as geom_poin.
- 89Choosing ChartsUse bars to compare categories, lines for trends, histograms for distributions, scatter pl.
- 90Base Plotsplot draws scatter plots and lines.
- 91Histograms and Boxplotshist shows a distribution and boxplot compares groups.
- 92Bar Chartsbarplot draws bars from a vector or table.
- 93Multiple Plotspar(mfrow) places several plots in one figure.
- 94ggplot2 Introductionggplot2 builds charts from data, aesthetics and layers added with +.
- 95ggplot2 Geomsgeom_bar, geom_histogram, geom_boxplot and geom_smooth draw different shapes.
- 96Facets, Colours and Themesfacet_wrap splits by group, colour maps a variable and theme changes the look.
- 97Saving Plotspng() and dev.off() or ggsave write images to files.
- 98Practice: Word FrequencySplit text and count with table.
- 99Practice: FizzBuzzVectorised version with ifelse.
- 100Practice: Class ReportCombine data frames, aggregation and sorting.
Advanced RPremium5 lessons
- 101Object Oriented RR has S3 (simple), S4 (formal) and R6 (reference) systems.
- 102Functional ProgrammingMap, Filter, Reduce and anonymous functions \(x) express data transformations without loop.
- 103Error HandlingtryCatch handles errors, warnings and finally code.
- 104Vectorisation and PerformanceVectorised code is far faster than loops.
- 105Packages and Projectsinstall.packages downloads from CRAN and library loads them.
R in practicePremium7 lessons
- 106R Markdown and QuartoR Markdown and Quarto mix text, code and results into reports, slides and websites.
- 107Shiny AppsShiny builds interactive web apps from R.
- 108Databases from RDBI connects R to databases like SQLite, MySQL and PostgreSQL.
- 109Web APIs and JSONhttr2 or httr make requests and jsonlite converts JSON to R objects with fromJSON and back.
- 110Machine Learning BasicsPackages like caret, tidymodels and randomForest train models.
- 111Reshaping with tidyrpivot_longer and pivot_wider change data between wide and long layouts.
- 112R Best PracticesUse projects, clear names, comments for why, functions instead of copy paste, version cont.