1 + 1[1] 2
mean(c(1, 2, 3))[1] 2
Jihong Zhang
Welcome to your first steps in applied multivariate statistics! In this tutorial, you will learn how to use R and RStudio to run code, work with data, create plots, and support reproducible analyses.
Install R before installing RStudio. R performs the computations; RStudio provides the interface for working with R.
RStudio is designed specifically for R programming and organizes the tools needed for an analysis in one interface.
.R files.R scripts with syntax highlightingScreenshot source: Posit RStudio User Guide: Pane Layout.
.R script rather than relying only on the Console.You can run R commands directly in the Console, but an .R script creates a record that you can revise and rerun. Enter the following commands in a script, then run each line with Ctrl+Enter (Cmd+Enter on Mac):
Screenshot source: Posit RStudio User Guide: Executing Code.
install.packages() once per machine; load each time with library().── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.2.0 ✔ readr 2.2.0
✔ forcats 1.0.1 ✔ stringr 1.6.0
✔ ggplot2 4.0.2 ✔ tibble 3.3.1
✔ lubridate 1.9.5 ✔ tidyr 1.3.2
✔ purrr 1.2.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
here() starts at /Users/jihong/Documents/Projects/website-jihong
You can also select Install in the Packages pane, enter the package names, and select Install in the dialog.
Screenshot source: Posit RStudio User Guide: Packages Pane.
readr::read_csv() for CSV; read.csv() is the base R alternative.heights.csv and inspect the data preview, variable names, and inferred data types..R script so the step is reproducible.Screenshot source: Posit RStudio User Guide: Local Data.
Create a folder called data in your project folder, download heights.csv into it, and run one of the following commands:
Use View() or select a data-frame object in the Environment pane to open RStudio’s spreadsheet-like Data Viewer.
In the Data Viewer, try these tasks:
Sorting and filtering in the Data Viewer help you inspect the data, but they do not document a reproducible transformation. Record substantive data changes in the R script.
Screenshot source: Posit RStudio User Guide: Data Viewer.
write_csv() or write.csv().select(), filter(), mutate(), summarize(), group_by().# A tibble: 3 × 2
cyl mean_mpg
<dbl> <dbl>
1 4 26.7
2 6 19.7
3 8 15.1
The Export button in the Plots pane can save a figure interactively. Recording ggsave() in the script also preserves the file name and dimensions.
Workflow source: Posit RStudio User Guide: Get Started.
here::here() for reliable paths.[1] "/Users/jihong/Documents/Projects/website-jihong/teaching/2024-07-21-applied-multivariate-statistics-esrm64503/Lecture01"
[1] "/Users/jihong/Documents/Projects/website-jihong"
Use File → New Project to start in a new directory, organize an existing directory, or obtain a project from version control.
Screenshot source: Posit RStudio User Guide: RStudio Projects.
R version 4.5.2 (2025-10-31)
Platform: aarch64-apple-darwin20
Running under: macOS Tahoe 26.5.2
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.1
locale:
[1] C.UTF-8/C.UTF-8/C.UTF-8/C/C.UTF-8/C.UTF-8
time zone: America/Chicago
tzcode source: internal
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] here_1.0.2 lubridate_1.9.5 forcats_1.0.1 stringr_1.6.0
[5] dplyr_1.2.0 purrr_1.2.1 readr_2.2.0 tidyr_1.3.2
[9] tibble_3.3.1 ggplot2_4.0.2 tidyverse_2.0.0
loaded via a namespace (and not attached):
[1] Matrix_1.7-4 gtable_0.3.6 jsonlite_2.0.0 compiler_4.5.2
[5] tidyselect_1.2.1 Rcpp_1.1.1 unigd_0.2.0 systemfonts_1.3.1
[9] scales_1.4.0 png_0.1-8 yaml_2.3.12 fastmap_1.2.0
[13] reticulate_1.45.0 lattice_0.22-9 R6_2.6.1 labeling_0.4.3
[17] generics_0.1.4 knitr_1.51 htmlwidgets_1.6.4 rprojroot_2.1.1
[21] tzdb_0.5.0 pillar_1.11.1 RColorBrewer_1.1-3 rlang_1.1.7
[25] stringi_1.8.7 xfun_0.56 S7_0.2.1 otel_0.2.0
[29] timechange_0.4.0 cli_3.6.5 withr_3.0.2 magrittr_2.0.4
[33] digest_0.6.39 grid_4.5.2 hms_1.1.4 lifecycle_1.0.5
[37] vctrs_0.7.1 evaluate_1.0.5 glue_1.8.0 farver_2.1.2
[41] httpgd_2.0.4 rmarkdown_2.30 tools_4.5.2 pkgconfig_2.0.3
[45] htmltools_0.5.9
Use ?function_name or help("function_name") to open documentation in the Help pane. Use example() to run a function’s documented examples.
Screenshot source: Posit RStudio User Guide: Pane Layout and Help.
tidyverse (readr, dplyr, tidyr, ggplot2).R scripts so you can rerun and inspect them---
title: "Make Friends with R and RStudio"
author: "Jihong Zhang"
format:
html:
code-tools: true
---
# Make Friends with R and RStudio
Welcome to your first steps in applied multivariate statistics! In this tutorial, you will learn how to use R and RStudio to run code, work with data, create plots, and support reproducible analyses.
------------------------------------------------------------------------
## 1. What Are R and RStudio?
- **R** (required): A powerful programming language for statistical computing and graphics.
- **RStudio**: An integrated development environment (IDE) that provides an editor, Console, object viewer, plot viewer, package tools, and help system for R. Download [RStudio Desktop](https://posit.co/download/rstudio-desktop/).
::: {.rmdnote}
Install R before installing RStudio. R performs the computations; RStudio provides the interface for working with R.
:::
------------------------------------------------------------------------
## 2. Getting Started with RStudio
RStudio is designed specifically for R programming and organizes the tools needed for an analysis in one interface.
### Key Features of RStudio
- **R-focused design**: Built specifically for R programming and statistical analysis
- **Four-panel layout**: Organized interface with Source, Console, Environment, and Files/Plots panels
- **Package management**: Easy package installation and loading through GUI
- **Project management**: RStudio Projects for organized, reproducible workflows
- **Git integration**: Built-in version control support
- **Script editor**: Write, save, and rerun analysis code in `.R` files
### RStudio Interface Layout
- **Source Editor (top-left)**: Write and edit `.R` scripts with syntax highlighting
- **Console (bottom-left)**: Interactive R console for running commands
- **Environment/History (top-right)**: View objects, variables, and command history
- **Files/Plots/Packages/Help (bottom-right)**: Navigate files, view plots, manage packages, access help
{fig-alt="RStudio interface with red labels identifying the Source pane at top left, Console at bottom left, Environment at top right, and Output at bottom right." width="85%"}
<small>Screenshot source: [Posit RStudio User Guide: Pane Layout](https://docs.posit.co/ide/user/ide/guide/ui/ui-panes.html).</small>
### Getting Started with RStudio
1. **Download**: Get RStudio Desktop from [posit.co/download/rstudio-desktop/](https://posit.co/download/rstudio-desktop/)
2. **Create projects**: Use File → New Project for organized workflows
3. **Customize layout**: Tools → Global Options → Pane Layout to adjust panels
4. **Install packages**: Use Tools → Install Packages or the Packages panel
### Essential RStudio Features
- **Code completion**: Tab completion for functions and variables
- **Help integration**: F1 on functions for instant help
- **Object inspector**: Click objects in Environment to view details
- **Plot history**: Navigate through previous plots in Plots panel
- **Addins**: Extend functionality with community-developed tools
### RStudio Keyboard Shortcuts
- **Run code**: Ctrl+Enter (Cmd+Enter on Mac)
- **New R script**: Ctrl+Shift+N (Cmd+Shift+N)
- **Save the current script**: Ctrl+S (Cmd+S)
- **Source the current script**: Ctrl+Shift+Enter (Cmd+Shift+Enter)
- **Go to line**: Ctrl+G (Cmd+G)
### A Basic RStudio Workflow
- Create or open an RStudio Project for the analysis.
- Write commands in an `.R` script rather than relying only on the Console.
- Run one line or a selected block with Ctrl+Enter (Cmd+Enter on Mac).
- Inspect data and model objects in the Environment pane.
- Review figures in the Plots pane and documentation in the Help pane.
- Save the script so the analysis can be rerun and checked.
------------------------------------------------------------------------
## 3. Running R Code in RStudio
You can run R commands directly in the Console, but an `.R` script creates a record that you can revise and rerun. Enter the following commands in a script, then run each line with Ctrl+Enter (Cmd+Enter on Mac):
{fig-alt="RStudio Source pane showing an R script containing View(mtcars), with the Run and Source buttons visible in the toolbar." width="90%"}
<small>Screenshot source: [Posit RStudio User Guide: Executing Code](https://docs.posit.co/ide/user/ide/guide/code/execution.html).</small>
```{r}
1 + 1
mean(c(1, 2, 3))
```
```{r}
#| eval: false
print("Hello, world!")
```
------------------------------------------------------------------------
## 4. Install and Load Packages
- Use `install.packages()` once per machine; load each time with `library()`.
```{r}
#| eval: false
install.packages(c("tidyverse", "readr", "ggplot2", "here"))
```
```{r}
library(tidyverse)
library(here)
```
You can also select **Install** in the Packages pane, enter the package names, and select **Install** in the dialog.
{fig-alt="RStudio Install Packages dialog with tidyverse entered as the package name and the Install dependencies option selected." width="55%"}
<small>Screenshot source: [Posit RStudio User Guide: Packages Pane](https://docs.posit.co/ide/user/ide/guide/ui/packages-pane.html).</small>
------------------------------------------------------------------------
## 5. Importing Data
- Prefer `readr::read_csv()` for CSV; `read.csv()` is the base R alternative.
### Task: Import a CSV with RStudio
1. Select **File → Import Dataset → From Text (readr)** or use **Import Dataset** in the Environment pane.
2. Select `heights.csv` and inspect the data preview, variable names, and inferred data types.
3. Review the **Code Preview**, then select **Import**.
4. Copy the generated import code into your `.R` script so the step is reproducible.
{fig-alt="RStudio Import Text Data wizard showing a CSV URL, a preview of penguin data, import options, and generated readr code in the Code Preview area." width="80%"}
<small>Screenshot source: [Posit RStudio User Guide: Local Data](https://docs.posit.co/ide/user/ide/guide/data/data-local.html).</small>
### Task: Import the Same File with Code
Create a folder called `data` in your project folder, download `heights.csv` into it, and run one of the following commands:
```{r}
#| eval: false
# Read CSV with readr
height_data <- readr::read_csv(here::here("data", "heights.csv"))
# Base R alternative
height_data_base <- read.csv(here::here("data", "heights.csv"))
```
------------------------------------------------------------------------
## 6. Inspecting Data in the Data Viewer
Use `View()` or select a data-frame object in the Environment pane to open RStudio's spreadsheet-like Data Viewer.
```{r}
#| eval: false
mpg_data <- ggplot2::mpg |>
dplyr::select(manufacturer, model, displ, cty, hwy)
View(mpg_data)
```
In the Data Viewer, try these tasks:
1. Select a column name to sort the rows.
2. Select **Filter** to define column-specific filters.
3. Use the search box to find matching values across columns.
4. Return to the script before changing the data.
{fig-alt="RStudio Data Viewer showing manufacturer, model, engine displacement, city mileage, and highway mileage columns with Filter and Search controls." width="90%"}
::: {.rmdnote}
Sorting and filtering in the Data Viewer help you inspect the data, but they do not document a reproducible transformation. Record substantive data changes in the R script.
:::
<small>Screenshot source: [Posit RStudio User Guide: Data Viewer](https://docs.posit.co/ide/user/ide/guide/data/data-viewer.html).</small>
------------------------------------------------------------------------
## 7. Exporting Data
- Save data to disk using `write_csv()` or `write.csv()`.
```{r}
#| eval: false
readr::write_csv(
height_data,
here::here("outputs", "clean-height-data.csv")
)
write.csv(
height_data_base,
here::here("outputs", "clean-height-data-base.csv"),
row.names = FALSE
)
```
------------------------------------------------------------------------
## 8. Basic Data Wrangling with dplyr
- Core verbs: `select()`, `filter()`, `mutate()`, `summarize()`, `group_by()`.
```{r}
library(dplyr)
mtcars_summary <- mtcars |>
group_by(cyl) |>
summarize(mean_mpg = mean(mpg), .groups = "drop")
head(mtcars_summary)
```
------------------------------------------------------------------------
## 9. Basic Plot with ggplot2
- Create a scatterplot and map aesthetics.
```{r}
library(ggplot2)
mpg_plot <- ggplot(
mtcars,
aes(x = wt, y = mpg, color = factor(cyl))
) +
geom_point(size = 2) +
labs(color = "Cylinders", x = "Weight", y = "MPG")
mpg_plot
```
### Task: Save the Plot Reproducibly
The **Export** button in the Plots pane can save a figure interactively. Recording `ggsave()` in the script also preserves the file name and dimensions.
```{r}
#| eval: false
dir.create(here::here("outputs"), showWarnings = FALSE)
ggplot2::ggsave(
filename = here::here("outputs", "mtcars-scatterplot.png"),
plot = mpg_plot,
width = 6,
height = 4
)
```
<small>Workflow source: [Posit RStudio User Guide: Get Started](https://docs.posit.co/ide/user/ide/get-started/).</small>
------------------------------------------------------------------------
## 10. Working Directories and Projects
- Use RStudio Projects and `here::here()` for reliable paths.
```{r}
getwd()
here::here()
```
Use **File → New Project** to start in a new directory, organize an existing directory, or obtain a project from version control.
{fig-alt="RStudio New Project Wizard offering New Directory, Existing Directory, and Version Control as three project-creation choices." width="70%"}
<small>Screenshot source: [Posit RStudio User Guide: RStudio Projects](https://docs.posit.co/ide/user/ide/guide/code/projects.html).</small>
------------------------------------------------------------------------
## 11. Reproducibility
- Record your session details for reproducibility.
```{r}
sessionInfo()
```
------------------------------------------------------------------------
## 12. Getting Help
Use `?function_name` or `help("function_name")` to open documentation in the Help pane. Use `example()` to run a function's documented examples.
```{r}
#| eval: false
?mean
help("mean")
example(mean)
```
{fig-alt="RStudio Console on the left showing paste0 output and Help pane on the right displaying examples for the base paste function." width="90%"}
<small>Screenshot source: [Posit RStudio User Guide: Pane Layout and Help](https://docs.posit.co/ide/user/ide/guide/ui/ui-panes.html#help).</small>
------------------------------------------------------------------------
## 13. Next Steps
- Explore the `tidyverse` (readr, dplyr, tidyr, ggplot2)
- Organize each analysis in an RStudio Project
- Save your commands in `.R` scripts so you can rerun and inspect them
- Practice by importing a dataset, cleaning it, summarizing, and plotting