Tsallaka zuwa abun ciki
Justice Tech School

R Tutorial

The language of statistics, data analysis and charts.

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