--- title: "Tutorial 00 — Get Up and Running with R, RStudio, Quarto & VS Code" subtitle: "Install the workshop packages, learn how packages and Quarto work, and get your local tools (RStudio and VS Code) ready for Day 1" author: "Single Cell RNA-seq Workshop" format: html: toc: true toc-depth: 3 code-fold: false code-overflow: wrap highlight-style: github embed-resources: true execute: eval: false echo: true warning: false message: false editor: visual --- ::: {.callout-note title="Running the code in this tutorial"} Every code chunk here is tagged with `#| eval: false`, so the published page shows the code **without running it**. To run it yourself, open the downloaded `.qmd` in **RStudio**: - **Run one chunk:** click the green ▶ (*Run Current Chunk*) at the chunk's top-right, or press *Ctrl/Cmd + Enter*. This runs the chunk **regardless of its `eval` setting** — the easiest way to work through the tutorial interactively. - **Run a chunk on render:** change that chunk's `#| eval: false` to `#| eval: true` (or delete the line) so it executes when the document is rendered. - **Render the whole tutorial:** click the **Render** button in RStudio (or run `quarto render` in a terminal) to execute the chunks top-to-bottom and knit a finished HTML. To run everything on render, set `eval: true` once in the YAML header at the top. ::: ## About this tutorial A short **"get up and running"** tutorial for the very start of Day 1. It does **not** replace the Day 0 computational refresher — it's a fast reminder for participants who didn't attend Day 0, and the place where everyone installs the R packages the workshop needs. By the end you will have: - every R / Bioconductor package the workshop uses, installed - a working understanding of how packages are installed, loaded, and updated - **LaTeX** installed so Quarto can render to PDF - the basics of writing and rendering a **Quarto** document ::: callout-note **Companion lecture:** [Lecture 00 — Tools and Foundational Concepts](../Lecture_Folder/Lecture_00_Tools_Found_Concepts.html) · [Chapter 0 — Overview](../Resources_Folder/Chapter_00_Overview.html). If R or the command line are rusty, see the [P2 — R & RStudio](../Resources_Folder/Chapter_P2_R_and_CommandLine.html) reading. ::: ::: {.callout-tip title="How to use this page"} The rendered HTML shows the code but does **not** execute it. To run it yourself, download the source — Tutorial_00_Setup_RStudio_Packages.qmd — then **drop the trailing `.txt`** so the filename ends in `.qmd`, open it in RStudio, and run it chunk by chunk. ::: ## 1. How packages work in R R itself is small; almost everything we do comes from **packages** — bundles of functions other people have written. The key idea: > **You install a package once; you load it every session.** - **Installing** downloads the package onto your computer. You do this *once* (and again only when you update). Installs come from **CRAN** with `install.packages()` or from **Bioconductor** with `BiocManager::install()`. - **Loading** makes an installed package's functions available in your *current* R session. You do this *every time you start R* and want to use that package, with `library()`. ```{r} #| label: M0-install_packages_tidyverse_once #| eval: false install.packages("tidyverse") # ONCE — downloads & installs onto your machine library(tidyverse) # EVERY SESSION — makes its functions usable now ``` If you restart R (or open a fresh RStudio session) you do **not** need to re-install — but you **do** need to re-`library()` the packages your code uses. That's why every tutorial begins with a `library(...)` block. ::: callout-tip **Loading through the RStudio window.** You can also load a package without typing: in the **Packages** pane (bottom-right of RStudio), find the package in the list and tick its checkbox — RStudio runs `library()` for you and echoes the command in the Console. Unticking it calls `detach()`. Even so, writing `library()` *in your script* is the better habit, because it makes the script reproducible: anyone (including future you) can see exactly what it needs to run. ::: You can also call a single function without loading the whole package using `package::function()` — for example `muscData::Kang18_8vs8()`. We use this occasionally to avoid name clashes. ## 2. Install the workshop packages Paste the **entire block** below into your R **Console**. The first run takes **20–60 minutes** depending on your machine and whether your platform builds from source — **do it before the workshop, not the morning of.** ### Core packages — for the in-person workshop (modules P1–10) Paste the **entire block** below into your R **Console**. This installs **everything you need for Tuesday–Friday**. The first run takes **20–60 minutes** depending on your machine and whether your platform builds from source — **do it before the workshop, not the morning of.** ```{r} #| label: M0-cran #| eval: false # CRAN cran_pkgs <- c( "tidyverse", # dplyr, ggplot2, tidyr, readr, purrr, tibble, stringr, forcats "Seurat", # core scRNA-seq workflow (workshop default) "remotes", # GitHub installs "BiocManager", # Bioconductor installer "patchwork", # combining ggplots "presto", # fast Wilcoxon for FindMarkers / FindAllMarkers "harmony", # batch integration (Module 05) "ggrepel", # non-overlapping labels on UMAPs "svglite" # write figures as editable .svg (alongside .png) for Illustrator ) install.packages(setdiff(cran_pkgs, rownames(installed.packages()))) # Bioconductor if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") bioc_pkgs <- c( "SingleCellExperiment", "scran", "scater", "scuttle", "DropletUtils", # EmptyDrops, knee-point cell calling (Module 01) "scDblFinder", # doublet detection (Module 01) "SoupX", # ambient-RNA correction (Module 01) "DESeq2", "edgeR", "limma", # (pseudo)bulk differential expression (Module 06) "apeglm", # LFC shrinkage for ranking/MA plots (Module 06, lfcShrink) "airway", # bulk RNA-seq primer dataset (Module 06, Part A) "fgsea", "clusterProfiler", "ReactomePA", "enrichplot", # functional analysis (Module 07) "org.Hs.eg.db", "org.Mm.eg.db", # gene-ID maps (Module 07) "miloR", # differential abundance (Module 08) "muscData" # ifnb (Kang18_8vs8) loader (Modules 01–08) ) BiocManager::install(setdiff(bioc_pkgs, rownames(installed.packages())), update = FALSE, ask = FALSE) # GitHub / R-universe remotes::install_github("satijalab/seurat-data", quiet = TRUE, upgrade = "never") # SeuratData # Azimuth provides reference-based annotation (Module 04). It downloads its PBMC # reference on first use — no Bioconductor reference-data packages needed. remotes::install_github("satijalab/azimuth", quiet = TRUE, upgrade = "never") # Azimuth (Module 04) # Pre-warm the ifnb cache (Kang et al. 2017; Modules 01–08) — first call downloads ~25 MB. invisible(muscData::Kang18_8vs8()) ``` ::: callout-note The first install will take 20–60 minutes depending on your machine and whether your platform is building from source. **Run it before the workshop, not the morning of.** ::: ### Bonus packages — only for the self-paced bonus modules (11–17) You do **not** need these for the in-person workshop. Install a group **only when you reach that bonus module** — several (`monocle3`, `CellChat`, `WGCNA`) are large or need system libraries, so installing them up front just slows you down. (This block is not run here.) ``` {r} #| eval: false # Module 13 — Co-expression networks (WGCNA) install.packages(c("WGCNA", "CorLevelPlot", "gridExtra")) BiocManager::install("GEOquery", update = FALSE, ask = FALSE) # Module 14 — Trajectory & cell–cell communication BiocManager::install("slingshot", update = FALSE, ask = FALSE) remotes::install_github("cole-trapnell-lab/monocle3", upgrade = "never") remotes::install_github("jinworks/CellChat", upgrade = "never") # CytoTRACE installs from a tarball — see https://cytotrace.stanford.edu # Module 15 — scATAC-seq with Signac install.packages("Signac") BiocManager::install(c("EnsDb.Hsapiens.v75", "rtracklayer", "GenomeInfoDb"), update = FALSE, ask = FALSE) # Module 16 — Spatial transcriptomics SeuratData::InstallData("stxBrain") # ~50 MB Visium mouse brain remotes::install_github("dmcable/spacexr", upgrade = "never")# RCTD deconvolution # Module 17 — FAIR data & sharing install.packages(c("jsonlite", "yaml")) remotes::install_github("mojaveazure/seurat-disk", upgrade = "never") # SeuratDisk remotes::install_github("cellgeni/sceasy", upgrade = "never") # robust Seurat->AnnData on Seurat v5 ``` ## 3. Keeping R and your packages up to date Software moves. A package you installed last year may be several versions behind, and stale versions can collide with newer code. There are two separate things to keep current: **your packages** and **R itself**. **Update your packages (any operating system):** ```{r} #| label: M0-update_packages_ask_false #| eval: false update.packages(ask = FALSE) # update CRAN packages BiocManager::install() # check for / update Bioconductor packages BiocManager::valid() # report packages that are out of sync ``` In RStudio you can do the CRAN part through a window: **Tools → Check for Package Updates…**, or the **Update** button in the **Packages** pane. **Updating R itself is separate from updating packages, and it differs by OS:** - **Windows** — the `installr` package automates it: `install.packages("installr"); installr::updateR()`. It can offer to copy your installed packages over to the new R version. - **macOS** — download the latest `.pkg` from and run the installer (or `brew install --cask r` if you use Homebrew). - **Linux** — use your distribution's package manager: `sudo apt update && sudo apt install --only-upgrade r-base` on Ubuntu/Debian (after enabling the CRAN APT repo for the newest release), or `sudo dnf upgrade R` on Fedora. ::: callout-warning **Major R upgrades need package re-installs.** Moving from R 4.3 to 4.4 (a change in the *second* number) starts a fresh package library, so plan to re-run the install block in Section 2. *Minor* upgrades (4.4.0 → 4.4.1) keep your existing packages. ::: ## 4. Install LaTeX (for Quarto → PDF) Quarto renders to HTML with no extra software, but rendering to **PDF** needs a LaTeX engine. The easiest, cross-platform option is **TinyTeX**, installed from R: ```{r} #| label: M0-install_packages_tinytex #| eval: false install.packages("tinytex") tinytex::install_tinytex() # one-time; ~1–2 min, no admin rights needed ``` This works the same on Mac, Windows, and Linux, and won't interfere with any system LaTeX you may already have. After restarting RStudio, confirm it with: ```{r} #| label: M0-tinytex_tinytex_should_return #| eval: false tinytex::is_tinytex() # should return TRUE ``` ## 5. Quarto in five minutes — Markdown, code, and rendering The tutorials are **Quarto** documents (files ending in `.qmd`). A Quarto file mixes plain-text **Markdown** with runnable **code chunks**, and renders to a polished document. **Markdown** is lightweight, readable formatting: ``` markdown # A big heading ## A smaller heading Plain text with **bold**, *italic*, and `inline code`. - a bullet - another bullet [a link](https://quarto.org) ``` **Code chunks** are fenced blocks tagged with a language. In RStudio, click the green ▶ "Run Current Chunk" arrow at the top-right of a chunk to run just that chunk (or press *Ctrl/Cmd + Enter* to run the current line or selection): ```` markdown ```{r} #| label: M0-quarto_demo_chunk 1 + 1 library(tidyverse) ``` ```` ::: callout-tip **Running a chunk even when `#| eval: false` is set.** Every chunk in these tutorials is tagged `#| eval: false` (and the YAML header sets it too), so the **published HTML shows the code without running it**. That setting only affects **rendering** — it never stops you running the code yourself. With the `.qmd` open in RStudio (or VS Code with the R extension), put your cursor in a chunk and: - click the green **▶ Run Current Chunk** arrow at the chunk's top-right, **or** - press **Ctrl/Cmd + Enter** to run the current line/selection, **or** - press **Ctrl/Cmd + Shift + Enter** to run the entire chunk. These execute the code in your live R session immediately, *ignoring* `eval: false`. This is the normal way to work through a tutorial interactively. If you also want a chunk to run **on render**, change its `#| eval: false` to `#| eval: true` (or delete the line); to run everything on render, set `eval: true` once in the YAML header. ::: **Rendering** turns the *whole* `.qmd` — prose, code, **and the code's output** (tables, plots) — into a finished document. Click the **Render** button in RStudio, or run `quarto render yourfile.qmd` in a terminal. Quarto executes every code chunk from top to bottom and stitches the results into the output. **One source, many outputs.** The same `.qmd` can produce different formats just by changing the `format:` line in the YAML header at the top of the file: ``` yaml format: html # a web page (what these tutorials use) format: pdf # a PDF (needs LaTeX — see Section 4) format: docx # a Word document ``` So you can write an analysis once and produce an HTML page for the web, a PDF for a supplement, and a Word document for a collaborator — all from the same file. **Math.** Quarto typesets **LaTeX math** anywhere in your prose — handy for writing down the models behind an analysis. Wrap an expression in **single** dollar signs for *inline* math, or **double** dollar signs for a *display* equation centered on its own line. *Inline* sits in a sentence. Writing `the Poisson rate is $\lambda$, and $P(A \mid B)$ is a conditional probability` renders as: the Poisson rate is $\lambda$, and $P(A \mid B)$ is a conditional probability. *Display* equations go between `$$ … $$` on their own lines. For example, this source: ``` markdown $$ P(X = k) = \frac{\lambda^{k} e^{-\lambda}}{k!} $$ ``` renders as the Poisson probability mass function (the model behind UMI counts): $$ P(X = k) = \frac{\lambda^{k} e^{-\lambda}}{k!} $$ A few more you will meet in this workshop — **Bayes' theorem**, the foundation of probabilistic cell-type assignment: $$ P(\theta \mid x) = \frac{P(x \mid \theta)\, P(\theta)}{P(x)} $$ the **Gaussian (normal) density**, with mean $\mu$ and variance $\sigma^{2}$: $$ f(x) = \frac{1}{\sigma\sqrt{2\pi}}\, \exp\!\left(-\frac{(x-\mu)^{2}}{2\sigma^{2}}\right) $$ and two pieces of **calculus** — the definition of a derivative, and an expected value written as an integral: $$ f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} \qquad\qquad \mathbb{E}[X] = \int_{-\infty}^{\infty} x\, f(x)\, dx $$ Common building blocks: `\frac{a}{b}` (fraction), `x^{2}` / `x_{i}` (super/subscript), `\sum`, `\int`, `\lim`, `\sqrt{}`, `\mid` (the conditional bar), Greek letters like `\lambda`, `\mu`, `\sigma`, `\theta`, and `\mathbb{E}` for the expectation symbol. The [Appendix — Quarto & Markdown Syntax](../Resources_Folder/Appendix_I_Quarto_Markdown.html) has a fuller reference. ::: callout-tip New to Quarto? The [Quarto guide](https://quarto.org/docs/guide/) is excellent, and **[P2 — R & RStudio](../Resources_Folder/Chapter_P2_R_and_CommandLine.html)** covers the RStudio basics in more depth. ::: ## 6. VS Code on your laptop For this module you use **VS Code** (and RStudio) locally on your own machine — no cluster connection needed. VS Code is a free editor that works great for `.qmd` and `.R` files; install it from and add the **Quarto** and **R** extensions so you can run and render notebooks right in the editor. Connecting VS Code to UO's **Talapas** cluster over **Remote-SSH** — along with interactive sessions, Lmod modules, and SLURM batch jobs — is the **Friday** track covered in [Tutorial 09 — VS Code & SLURM Basics on Talapas](Tutorial_09_SLURM_Basics.html). You don't need any of that for the core modules (01–08) run this week. ## You're ready Once the install block has finished and TinyTeX is in place, your local tools (RStudio and VS Code) are ready for Day 1. If anything errored, the [FAQ](../FAQ.html) covers the most common install problems — and bring anything you can't resolve to the optional [Day 0](../Schedule.html#day-0-optional-computational-refresher) session.