class: center, middle, inverse, title-slide .title[ # Introduction to R ] .subtitle[ ## R Foundations for Data Analysis ] .author[ ### Guilherme Dias ] --- exclude: true count: false <link href="https://fonts.googleapis.com/css?family=Roboto|Source+Sans+Pro:300,400,600|Ubuntu+Mono&subset=latin-ext" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous"> <!-- ------------ Only edit title, subtitle & author above this ------------ --> --- name: content class: spaced # Contents 1. [The problem: life in spreadsheets](#whyR) ๐งจ 2. [What R is (and isn't)](#about) ๐งญ 3. [How R compares](#compare) โ๏ธ 4. [Thinking like a programmer](#programming_language) ๐ง 5. [Packages: standing on giants' shoulders](#packages) ๐ฆ 6. [Coding in the age of AI](#ai) ๐ค --- .pull-left-50[ Have you ever... * lost track of which Excel file made a figure? * redone an analysis by hand because data changed? * had a gene name silently turned into a date? * asked ChatGPT/Claude/Copilot to write code for you? ] .pull-right-50[ <br> ### If you answered **yes** to any of these... #### ...this course is for you. ] --- name: whyR # The GUI trap ๐งจ * Manual copy-pasting across Excel files * "Which version of `data_final_v3_REAL.xlsx` was this graph made from?" * No record of *what you clicked* * Silent gene name conversions (`SEPT9` `\(\rightarrow\)` `Sept-09`, `MARCH1` `\(\rightarrow\)` `1-Mar`) <br></br> <img src="images/excel-microsoft2.gif" width="35%" style="display: block; margin: auto;" /> -- <br></br> Gene-name autocorrection errors were found in roughly **1 in 5** genomics papers with Excel supplements (Ziemann *et al.*, *Genome Biology*, 2016). The HGNC eventually **renamed the genes** to stop it. --- name: about # Briefly about R ๐งญ .pull-left-50[ ### R is ... * a programming language **built for data & statistics** * free, open-source, and runs everywhere * driven by a core team **and** a huge community * the home of cutting-edge statistics and bioinformatics * a powerful computational tool in general ] -- .pull-right-50[ ### R is not ... * the fastest language * the most elegant language * the best tool for *every* job (e.g. building games or phone apps) ] --- name: compare # How does R compare? โ๏ธ <img src="slide_r_intro_files/figure-html/tool-comparison-1.png" width="2550" style="display: block; margin: auto;" /> --- # Cost & licensing ๐ธ | Tool | Academic / Student | Commercial | Licensing Model | | :--- | :---: | :---: | :--- | | **R / Python** | **$0** | **$0** | **Open-source** | | **MS Excel** | ~$100 / yr (M365) | ~$150 / yr | Subscription | | **GraphPad Prism** | ~$140 โ $260 / yr | ~$520 / yr | Per seat | | **Stata** | ~$125 โ $250 / yr | ~$1,000 โ $3,700 / yr | Per user / core | | **SPSS** | ~$100 โ $300 / yr | ~$1,200 โ $3,800 / yr | Per user / module | | **SAS** | Free (OnDemand, limited) | $10,000s+ / yr | Enterprise | <br> * Your code keeps working when you **change jobs, institutions or countries**. ๐ * Reviewers and collaborators can **re-run your analysis** without buying anything. --- # R vs. Python ๐ > **Python** is a general-purpose language that *can* do data analysis. > **R** was built *specifically* for data and statistics. -- ### Where R shines * **Data wrangling:** the `tidyverse` (`dplyr`, `tidyr`) reads almost like English. * **Plots:** `ggplot2` publication-quality figures with sensible defaults. * **Statistics & biology:** new methods often appear in R/Bioconductor first. * **Reporting:** **R Markdown**, **Quarto** and **Shiny** turn your code into reports, slides (like these!) and web apps. -- .content-box-green[ **It's not a war.** The concepts you learn here (variables, functions, data frames, loops) transfer directly to Python. ] --- name: demo class: middle # Three lines of R ๐ช ``` r ggplot(iris, aes(x = Petal.Length, y = Petal.Width, colour = Species)) + geom_point(size = 2, alpha = 0.8) + geom_smooth(method = "lm", se = FALSE) ``` <img src="slide_r_intro_files/figure-html/five-lines-1.png" width="1200" style="display: block; margin: auto;" /> New data? Change **one word** (`iris`) and press **Run**. Try that in Excel. --- # Why programming matters Point-and-click is easy for **today**. `coding` is a superpower for **tomorrow**. <div style="height: 40px;"></div> <img src="images/homer.jpg" width="50%" style="display: block; margin: auto;" /> --- # Why programming matters - **Self-documenting:** code records every step โ no guessing how you got your results. - **Instant re-runs:** new data? Press **Run** instead of remaking charts by hand. - **Fewer silent errors:** no hidden formulas, shifted cells or forgotten menu clicks. - **Scales effortlessly:** the same script handles 10 rows or 10 million. - **Shareable:** a script is a recipe anyone can follow. <img src="data/slide_programming/Data_Information_Knowledge.png" width="65%" style="display: block; margin: auto;" /> --- name: programming_language # Thinking like a programmer ๐ง Every programming language has three ingredients: .pull-left-50[ 1. **Data types** โ *what* are we working with? 2. **Syntax** โ *how* do we write it? 3. **Semantics** โ what does it *mean*? ] .pull-right-50[ Just like a natural language: * words (nouns, numbers...) * grammar * meaning ] --- # 1- Data types in R ๐งฑ .pull-left-50[ | Type | Example | `typeof()` | | :--- | :--- | :--- | | double | `3.14`, `-2` | `"double"` | | integer | `5L` | `"integer"` | | character | `"BRCA1"` | `"character"` | | logical | `TRUE`, `FALSE` | `"logical"` | | complex | `2+3i` | `"complex"` | Missing values: `NA` (fits any type) ] --- # 2 โ Syntax: how do we write it? The rules of the language's *grammar*. -- The same calculation in two languages: ``` 2 * 1 + 1 # R, Python, most languages (+ (* 2 1) 1) # Lisp ``` -- Break the grammar and the computer **refuses** to run: ``` r 2 * (1 + 1 ``` ``` ## Error in parse(text = input): <text>:2:0: unexpected end of input ## 1: 2 * (1 + 1 ## ^ ``` **Good news:** syntax errors are loud and easy to fix. --- # 3 โ Semantics: what does it *mean*? Grammatically correct โ meaningful: * *Colorful yellow sleeps on a crazy wave.* โ no meaning * *There is $500 on his empty bank account.* โ internal contradiction -- The same is true for code: ``` r height <- 180 # cm weight <- 70 # kg bmi <- weight / height # runs fine... but is it right? bmi ``` ``` ## [1] 0.3888889 ``` -- .content-box-yellow[ BMI = weight (kg) / height (m)ยฒ. R happily computed **nonsense**. **Semantic errors are silent.** Only *you* can catch them. Remember this when using AI! ] --- name: topic2 # Where to start? .pull-left-50[ ``` r knitr::include_graphics("images/breakit.jpeg") ``` <img src="images/breakit.jpeg" width="395" style="display: block; margin: auto auto auto 0;" /> ] -- <br></br> *Decomposition* โ divide and rule. **Top-down approach:** define the big problem and split it into smaller ones. This is exactly how to work well with an AI assistant: break the problem into small, verifiable pieces. --- name: packages # Packages ๐ฆ .pull-left-50[ * ready-made functions, data & documentation * developed by the community * cover very diverse areas of science * uniformly structured and documented * organised in repositories: + [CRAN](https://cran.r-project.org) โ general purpose, 20,000+ packages + [Bioconductor](https://www.bioconductor.org) โ bioinformatics, 2,000+ packages + [GitHub](https://github.com) โ development versions + [R-universe](https://r-universe.dev) โ browse it all ] .pull-right-50[ <img src="data/slide_intro/packages.jpg" width="220pt" style="display: block; margin: auto;" /> <img src="images/tidyverse-icons.png" width="220pt" style="display: block; margin: auto;" /> ] --- name: CRAN # Working with packages โ a CRAN page <img src="data/slide_r_environment/ggplot2_CRAN.png" width="100%" style="display: block; margin: auto;" /> **Tip:** the *Reference manual* and *Vignettes* are your best friends (and great context to give an AI assistant!). --- name: pkg_cran_inst # Installing packages Only a few packages come pre-installed: ``` r library(modelr) ``` Install **once** per computer: ``` r install.packages("ggplot2") ``` Load **every** session: ``` r library(ggplot2) # stops with an error if the package is missing require(ggplot2) # only warns, returns FALSE โ handy inside functions ``` .footnote[Analogy: `install.packages()` = buying a book. `library()` = taking it off the shelf.] --- name: work_pkg_details exclude: true # Installing packages โ details Choose a specific mirror (e.g. if your default one is down): ``` r install.packages("ggplot2", repos = "https://cloud.r-project.org") ``` Sometimes no pre-built version exists for your platform, so you install from **source code**: ``` r install.packages("path/to/ggplot2_3.5.1.tar.gz", repos = NULL, type = "source") ``` --- name: pkg_github # Packages โ GitHub More and more developers share packages via GitHub. Use `remotes` (or `devtools`, which includes it): ``` r install.packages("remotes") remotes::install_github("talgalili/installr") # "username/repo" ``` .pull-center-50[ <img src="images/installr.png" width="650pt" style="display: block; margin: auto;" /> ] .footnote[โ ๏ธ GitHub packages are not reviewed like CRAN/Bioconductor ones. Check who wrote it and whether it's maintained.] --- name: pkg_bioconductor # Packages โ Bioconductor <img src="data/slide_r_environment/logo_bioconductor.png" width="200pt" style="display: block; margin: auto;" /> First install the Bioconductor manager (once): ``` r if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") ``` Then install Bioconductor packages: ``` r BiocManager::install("GenomicRanges") ``` For more info, visit the [Bioconductor website](https://www.bioconductor.org/install/). --- # One tool to install them all: `pak` ๐ `pak` installs from **CRAN, Bioconductor and GitHub** with one function โ and it's fast. ``` r install.packages("pak") pak::pak("ggplot2") # CRAN pak::pak("GenomicRanges") # Bioconductor pak::pak("talgalili/installr") # GitHub ``` --- name: ai class: middle, center # Coding in the age of AI ๐ค ### "If AI can write code, why should I learn R?" --- # AI is a great assistant... AI tools (ChatGPT, Claude, GitHub Copilot, Positron Assistant...) can: * write a first draft of a script in seconds * explain cryptic error messages * translate code (Excel formula โ R, Python โ R) * suggest packages and functions you didn't know about * comment and document your code -- There are even R packages to call language models **from R**, e.g. `ellmer` (from the Posit / tidyverse team). -- .content-box-green[ Used well, AI makes learning R **faster**, not unnecessary. ] --- # ...but you are still the scientist ๐ฌ .pull-left-50[ ### AI can * produce code that **runs** * sound **very** confident * write a lot, fast ] .pull-right-50[ ### AI can also * invent functions or packages that **don't exist** * use the **wrong statistical test** * silently drop `NA`s, rows or samples * be wrong in ways that *look* right ] --- exclude: true # Spot the bug ๐ต๏ธ (an "AI-generated" snippet) > *Prompt: "Compare mean expression between treated and control samples."* ``` r expr <- data.frame( sample = paste0("S", 1:6), group = c("control", "control", "control", "treated", "treated", "treated"), value = c(5.1, 4.8, NA, 7.9, 8.4, 8.1) ) tapply(expr$value, expr$group, mean) ``` ``` ## control treated ## NA 8.133333 ``` * Why is `control` `NA`? What should we do about the missing value? * Is dropping it OK? Should we *report* it? * With n = 3 per group, which test is appropriate โ and why? These are **scientific** decisions. AI can't make them for you. --- # Working well with AI: a checklist โ 1. **Understand first, then prompt.** Know roughly what the answer should look like. 2. **Ask for small pieces**, not a whole analysis (*divide et impera* again!). 3. **Read every line.** If you can't explain it, don't run it on real data. 4. **Test on tiny data** where you already know the answer. 5. **Check that functions & packages actually exist** (`?function_name`). 6. **Save the code, not the chat.** A script is reproducible; a conversation is not. 7. **Never paste sensitive data** (e.g. patient data) into public AI tools. -- .content-box-green[ **AI writes the draft. You own the analysis.** That's why this course matters more now, not less. ] --- # A suggestion: - Try **not** to use AI agents - Instead, use AI chatbots to: - fix syntax errors - learn more about concepts --- name: recap # Recap * Why R? * About R. * R is a programming language for statistical computing and data analysis. * Packages and repositories. * Installing packages from CRAN, Bioconductor, GitHub. * AI and coding <!-- --------------------- Do not edit this and below --------------------- --> --- name: end_slide class: end-slide, middle count: false # Thank you! Questions? .end-text[ <p class="smaller"> <span class="small" style="line-height: 1.2;">Graphics from </span><img src="./assets/freepik.jpg" style="max-height:20px; vertical-align:middle;"><br> Created: 21-Oct-2026 โข <a href="https://www.scilifelab.se/">SciLifeLab</a> โข <a href="https://nbis.se/">NBIS</a> </p> ]