flowchart TD
A[RStudio Interface] --> B[Source Editor<br/>Top Left]
A --> C[Console<br/>Bottom Left]
A --> D[Environment/History<br/>Top Right]
A --> E[Files/Plots/Help<br/>Bottom Right]
B --> B1[Write and edit scripts]
B --> B2[Create Quarto documents]
C --> C1[Execute R commands]
C --> C2[View output]
D --> D1[View objects in memory]
D --> D2[See command history]
E --> E1[Browse files]
E --> E2[View plots]
E --> E3[Read documentation]
2 Getting Started with R, RStudio, and Reading Data
2.1 Learning Objectives
By the end of this chapter, you will be able to:
- Navigate the RStudio interface and understand the purpose of each pane
- Create and use R Projects for better project organization
- Understand working directories and file paths
- Distinguish between installing and loading R packages
- Create and render Quarto documents with YAML headers, markdown, and code chunks
- Read CSV files using
readr::read_csv() - Read Excel files using
readxl::read_excel() - Explore data using functions like
head(),tail(),glimpse(),str(), andsummary() - Understand the difference between data frames and tibbles
- Use R’s help system effectively
2.2 The RStudio Interface
When you open RStudio, you’ll see a workspace divided into several panes. Understanding each pane’s purpose will help you work efficiently.
2.2.1 The Four Main Panes
2.2.1.1 1. Source Editor (Top Left)
This is where you write and edit your code.
- Scripts (
.Rfiles): Plain R code - Quarto documents (
.qmdfiles): Mix code, text, and output - Multiple tabs: Work on several files at once
Keyboard shortcuts:
Cmd/Ctrl + Enter: Run current line or selectionCmd/Ctrl + Shift + Enter: Run entire scriptCmd/Ctrl + S: Save file
2.2.1.2 2. Console (Bottom Left)
This is where R actually runs and shows output.
- Type commands directly for quick tests
- See results from scripts
- View error messages and warnings
Console: Good for quick tests, exploring data Scripts: Good for saving your work, reproducibility
Always save important code in scripts or Quarto documents, not just in the console!
2.2.1.3 3. Environment/History (Top Right)
Environment tab:
- Shows all objects currently in memory (datasets, variables, functions)
- Click on dataset names to view them
- Shows object types and sizes
History tab:
- Shows previous commands
- Search through past code
- Reload old commands
To start fresh:
# Remove all objects from environment
rm(list = ls())Or click the broom icon in the Environment pane.
2.2.1.4 4. Files/Plots/Help (Bottom Right)
Files tab: Browse your project directory Plots tab: View visualizations Packages tab: Manage installed packages Help tab: Read function documentation Viewer tab: Preview HTML output
2.2.2 Customizing RStudio
Make RStudio work for you!
Tools → Global Options (or Cmd/Ctrl + ,):
- Appearance: Choose themes (dark mode, font size, colors)
- Code: Enable syntax highlighting, code completion
- Pane Layout: Rearrange panes to your preference
- Appearance → Choose a comfortable theme (I like “Tomorrow Night Bright” for dark mode)
- Code → Check “Soft-wrap R source files” (no horizontal scrolling)
- General → Uncheck “Restore .RData into workspace at startup” (for reproducibility)
- General → Uncheck “Save workspace to .RData on exit”
2.3 R Projects and Working Directories
2.3.1 What is a Working Directory?
The working directory is the folder where R looks for files and saves output.
Check your current working directory:
# Where am I?
getwd()[1] "/home/runner/work/ans-5000-book/ans-5000-book/chapters"
Problem: If you use absolute paths, your code won’t work on other computers:
# BAD: Absolute path (only works on my computer)
data <- read.csv("/Users/jane/Documents/my_project/data/cattle.csv")Solution: Use R Projects and relative paths!
2.3.2 What is an R Project?
An R Project is a special file (.Rproj) that:
- Sets the working directory to the project folder automatically
- Keeps all project files organized
- Makes code portable across computers
- Tracks your workspace and settings
2.3.3 Creating an R Project
Method 1: New Project
- File → New Project…
- Choose:
- New Directory: Start from scratch
- Existing Directory: Use an existing folder
- Version Control: Clone from Git/GitHub
- Name your project (e.g.,
ans500_cattle_analysis) - Choose where to save it
- Click Create Project
Method 2: From Existing Folder
If you already have a project folder:
- Navigate to the folder in RStudio’s Files pane
- More → Set As Working Directory
- File → New Project → Existing Directory
Benefits:
- Reproducibility: Code works on any computer
- Organization: Everything in one place
- Convenience: No more
setwd()! - Portability: Easy to share with collaborators
2.3.4 The here Package
Even better than relative paths: use the here package!
# Install once
install.packages("here")
# Load the package
library(here)
# Read data using here()
cattle <- read.csv(here("data", "raw", "cattle_weights.csv"))
# Save plots using here()
ggsave(here("output", "figures", "weight_plot.png"))Why here is awesome:
- Works from any subdirectory
- Works in Quarto documents
- Works across operating systems (Mac, Windows, Linux)
- Makes paths explicit and readable
2.4 Installing and Loading Packages
R’s power comes from packages—collections of functions written by the community.
2.4.1 Packages vs Libraries
Package = App on your phone Library = Installing/opening the app
Package: A collection of functions, data, and documentation Library: The folder where packages are stored
2.4.2 Installing Packages
You only need to install a package once (or when updating).
# Install a single package
install.packages("readr")
# Install multiple packages
install.packages(c("readr", "dplyr", "ggplot2"))
# Or install the tidyverse (includes many packages)
install.packages("tidyverse")- Put package names in quotes:
install.packages("readr") - Requires internet connection
- May take a few minutes for large packages
- Choose a CRAN mirror (any US mirror works)
2.4.3 Loading Packages
You need to load a package every time you start R.
# Load packages (no quotes!)
library(readr)
library(dplyr)
# Or load everything at once
library(tidyverse)# Do this ONCE:
install.packages("tidyverse")
# Do this EVERY SESSION:
library(tidyverse)Think of it like installing an app once, but opening it every time you want to use it.
2.4.4 Common Package Errors
Error: package not found
library(readr)
# Error: there is no package called 'readr'Solution: Install the package first!
install.packages("readr")
library(readr)Error: could not find function
read_csv("data.csv")
# Error: could not find function "read_csv"Solution: Load the package!
library(readr) # Now read_csv() is available2.4.5 Understanding CRAN
CRAN (Comprehensive R Archive Network) is the official repository for R packages.
- Over 20,000 packages available
- All packages are tested and documented
- Safe to install from CRAN
Other sources:
- Bioconductor: Bioinformatics packages
- GitHub: Development versions of packages
2.4.6 Package Documentation
Every package has documentation:
# View package overview
help(package = "readr")
# See all functions in a package
library(help = "readr")
# Read vignettes (tutorials)
vignette(package = "readr")
vignette("readr")2.5 Quarto Documents
Quarto is a publishing system that lets you combine code, text, and output in a single document.
2.5.1 Why Use Quarto?
Traditional workflow:
- Analyze data in R
- Copy results to Word/Excel
- Insert plots manually
- Write explanation
- If data changes: Repeat all steps 😫
Quarto workflow:
- Write code and explanation together
- Render with one click
- If data changes: Just re-render! ✨
With Quarto:
- Code and results are never out of sync
- Anyone can reproduce your analysis
- Updating is automatic
- Professional output (HTML, PDF, Word)
2.5.2 Creating a Quarto Document
File → New File → Quarto Document
- Enter title and author
- Choose output format (HTML recommended to start)
- Click Create
You’ll get a template with example content.
2.5.3 Anatomy of a Quarto Document
A Quarto document (.qmd) has three main components:
flowchart LR
A[Quarto Document] --> B[YAML Header]
A --> C[Markdown Text]
A --> D[Code Chunks]
B --> B1[Metadata and settings]
C --> C1[Formatted text]
D --> D1[Executable R code]
2.5.4 1. YAML Header
At the top of every Quarto document, between --- markers:
---
title: "My First Analysis"
author: "Your Name"
date: today
format:
html:
toc: true
code-fold: false
theme: cosmo
execute:
warning: false
message: false
---Common options:
title,author,date: Document metadataformat: Output type (html, pdf, docx)toc: true: Add table of contentscode-fold: true: Hide code by default (click to show)theme: Visual appearanceexecute: Control code execution
- Indentation matters (use 2 spaces)
- Colons need a space after them
- Use
todayfor automatic date - If you get an error, check your indentation!
2.5.5 2. Markdown Text
Markdown is a simple way to format text:
# Level 1 Header
## Level 2 Header
### Level 3 Header*italic* or _italic_
**bold** or __bold__
***bold italic***Unordered list:
- Item 1
- Item 2
- Sub-item
Numbered list:
1. First
2. Second
3. Third[Link text](https://example.com)
[R for Data Science](https://r4ds.hadley.nz/)2.5.6 3. Code Chunks
Code chunks contain R code that executes when you render:
```{r}
# R code goes here
x <- 1:10
mean(x)
```Insert code chunk:
- Click Insert → Code Chunk → R
- Or use keyboard shortcut:
Cmd/Ctrl + Option + I(Mac) /Ctrl + Alt + I(Windows)
2.5.6.1 Code Chunk Options
Control how code chunks behave with options:
```{r}
#| label: load-packages
#| echo: true
#| eval: true
#| warning: false
#| message: false
library(tidyverse)
```Common options:
label: Name the chunk (optional, but helpful)echo: true/false: Show/hide code in outputeval: true/false: Run/don’t run codewarning: false: Hide warning messagesmessage: false: Hide package loading messagesinclude: false: Run code but show nothing in output
If you’ve used R Markdown before:
- Quarto uses
#|for chunk options (instead of{r option=value}) - YAML syntax is slightly different
- Quarto has more features and better outputs
- Most R Markdown code works in Quarto!
2.5.7 Rendering Your Document
Render = Execute all code and create output document
Three ways to render:
- Click Render button (top of source pane)
- Keyboard shortcut:
Cmd/Ctrl + Shift + K - Command line:
quarto render document.qmd
Output:
- HTML: Opens in Viewer or browser
- PDF: Requires LaTeX (install TinyTeX)
- Word: Opens in Microsoft Word
HTML output is easiest:
- No additional software needed
- Interactive features (table of contents, code folding)
- Easy to share (single file)
- Fast rendering
2.5.8 Example Quarto Document
Here’s a complete minimal example:
---
title: "Cattle Weight Analysis"
author: "Your Name"
date: today
format: html
---
## Introduction
This analysis examines cattle weights from our feed trial.
## Load Data
```{r}
#| message: false
library(readr)
cattle <- read_csv("data/raw/cattle_weights.csv")
```
## Summary Statistics
The average initial weight was:
```{r}
mean(cattle$initial_weight_kg)
```
## Conclusion
We found interesting patterns in the data.2.6 Reading CSV Files
CSV (Comma-Separated Values) is the most common data format for analysis.
2.6.1 Why CSV?
- Plain text: Open in any editor
- Universal: Works with all software
- Version control friendly: Git can track changes
- Fast: Quick to read and write
- Reliable: No Excel date conversion errors!
2.6.2 The readr Package
The readr package (part of tidyverse) provides read_csv():
# Load the package
library(readr)
# Read a CSV file
cattle <- read_csv("data/raw/cattle_weights.csv")2.6.3 Reading Your First CSV
Let’s read the cattle weights data:
library(readr)
# Read CSV file
cattle <- read_csv(here::here("data", "raw", "cattle_weights.csv"))Rows: 20 Columns: 7
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (4): animal_id, breed, sex, treatment
dbl (2): initial_weight_kg, final_weight_kg
date (1): birth_date
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# View first few rows
head(cattle)# A tibble: 6 × 7
animal_id birth_date breed sex initial_weight_kg final_weight_kg treatment
<chr> <date> <chr> <chr> <dbl> <dbl> <chr>
1 C001 2023-03-15 Angus M 285 520 High_Pro…
2 C002 2023-03-18 Herefo… F 270 485 Standard
3 C003 2023-03-20 Angus M 290 535 High_Pro…
4 C004 2023-03-22 Charol… F 295 510 Control
5 C005 2023-03-25 Angus M 280 500 Standard
6 C006 2023-04-01 Herefo… F 275 495 High_Pro…
When you run read_csv():
- R reads the file from disk
- Parses column types automatically
- Creates a tibble (tidyverse data frame)
- Prints a message showing column types
- Assigns the result to
cattle
2.6.4 read_csv() vs read.csv()
R has two functions for reading CSVs:
| Feature | read.csv() (base R) |
read_csv() (readr) |
|---|---|---|
| Speed | Slower | Faster |
| Output | data.frame | tibble (better) |
| Column types | Less reliable | Smart guessing |
| Progress bar | No | Yes (for large files) |
| Strings as factors | Yes (annoying) | No |
read_csv()
The tidyverse version (read_csv() with underscore) is superior:
- Faster for large files
- Better column type guessing
- More consistent behavior
- Better error messages
2.6.5 Common read_csv() Options
# Skip first row
data <- read_csv("file.csv", skip = 1)
# Specify column types manually
data <- read_csv("file.csv",
col_types = cols(
animal_id = col_character(),
weight_kg = col_double(),
treatment = col_factor()
)
)
# Handle missing values
data <- read_csv("file.csv", na = c("", "NA", "N/A", "-", "."))
# No column names in file
data <- read_csv("file.csv", col_names = FALSE)
# Custom column names
data <- read_csv("file.csv",
col_names = c("id", "weight", "treatment")
)2.6.6 File Paths
# DON'T DO THIS
data <- read_csv("/Users/jane/Documents/project/data/cattle.csv")Problem: Only works on Jane’s computer!
# Better
data <- read_csv("data/raw/cattle.csv")Works if: Your working directory is the project root
# Best practice
library(here)
data <- read_csv(here("data", "raw", "cattle.csv"))Works: Anywhere, any time!
2.7 Reading Excel Files
While we prefer CSV for analysis, sometimes you need to read Excel files.
2.7.1 The readxl Package
# Install once
install.packages("readxl")
# Load every session
library(readxl)2.7.2 Reading an Excel File
library(readxl)
# Read Excel file
feed <- read_excel(here::here("data", "raw", "feed_records.xlsx"))
# View first few rows
head(feed)# A tibble: 6 × 6
pen_id week feed_type feed_consumed_kg avg_pen_weight_kg notes
<dbl> <dbl> <chr> <dbl> <dbl> <chr>
1 1 1 Grain_A 419. 301. Normal consumption
2 1 2 Grain_A 399. 378. Slight decrease
3 1 3 Grain_A 496 346. Normal
4 1 4 Grain_A 427 367. Increased intake
5 1 5 Grain_A 535. 341. Normal
6 2 1 Grain_B 475 406. Normal consumption
2.7.3 Excel File Options
# Specify sheet by name
data <- read_excel("file.xlsx", sheet = "Sheet2")
# Specify sheet by number
data <- read_excel("file.xlsx", sheet = 2)
# Skip rows
data <- read_excel("file.xlsx", skip = 3)
# Specify column types
data <- read_excel("file.xlsx",
col_types = c("text", "numeric", "date")
)
# Read specific range (like Excel: A1:D10)
data <- read_excel("file.xlsx", range = "A1:D10")
# Handle missing values
data <- read_excel("file.xlsx", na = c("", "NA", "N/A"))2.7.4 List Sheets in Excel File
# See all sheet names
excel_sheets(here::here("data", "raw", "feed_records.xlsx"))[1] "Sheet1"
2.7.5 Read Multiple Sheets
# Read all sheets into a list
library(purrr)
sheets <- excel_sheets("file.xlsx")
all_data <- map(sheets, ~ read_excel("file.xlsx", sheet = .x))
names(all_data) <- sheets- Date conversions: Excel loves turning things into dates
- Formula errors:
read_excel()reads values, not formulas - Hidden rows/columns: Will be included
- Merged cells: Can cause problems
- Formatting: Lost when importing (colors, fonts)
Best practice: Export to CSV from Excel before analysis!
2.8 Exploring Your Data
Once you’ve loaded data, the first step is exploration.
2.8.1 First Look Functions
View first or last rows:
# First 6 rows (default)
head(cattle)# A tibble: 6 × 7
animal_id birth_date breed sex initial_weight_kg final_weight_kg treatment
<chr> <date> <chr> <chr> <dbl> <dbl> <chr>
1 C001 2023-03-15 Angus M 285 520 High_Pro…
2 C002 2023-03-18 Herefo… F 270 485 Standard
3 C003 2023-03-20 Angus M 290 535 High_Pro…
4 C004 2023-03-22 Charol… F 295 510 Control
5 C005 2023-03-25 Angus M 280 500 Standard
6 C006 2023-04-01 Herefo… F 275 495 High_Pro…
# First 3 rows
head(cattle, n = 3)# A tibble: 3 × 7
animal_id birth_date breed sex initial_weight_kg final_weight_kg treatment
<chr> <date> <chr> <chr> <dbl> <dbl> <chr>
1 C001 2023-03-15 Angus M 285 520 High_Pro…
2 C002 2023-03-18 Herefo… F 270 485 Standard
3 C003 2023-03-20 Angus M 290 535 High_Pro…
# Last 6 rows
tail(cattle)# A tibble: 6 × 7
animal_id birth_date breed sex initial_weight_kg final_weight_kg treatment
<chr> <date> <chr> <chr> <dbl> <dbl> <chr>
1 C015 2023-05-05 Angus M 288 520 Standard
2 C016 2023-05-10 Herefo… F 275 485 Control
3 C017 2023-05-15 Angus M 292 540 High_Pro…
4 C018 2023-05-18 Charol… F 302 545 Standard
5 C019 2023-05-22 Herefo… M 280 500 Control
6 C020 2023-05-25 Angus F 270 480 High_Pro…
Transposed view of data:
library(dplyr)
glimpse(cattle)Rows: 20
Columns: 7
$ animal_id <chr> "C001", "C002", "C003", "C004", "C005", "C006", "C00…
$ birth_date <date> 2023-03-15, 2023-03-18, 2023-03-20, 2023-03-22, 202…
$ breed <chr> "Angus", "Hereford", "Angus", "Charolais", "Angus", …
$ sex <chr> "M", "F", "M", "F", "M", "F", "M", "F", "M", "F", "M…
$ initial_weight_kg <dbl> 285, 270, 290, 295, 280, 275, 285, 300, 278, 272, 30…
$ final_weight_kg <dbl> 520, 485, 535, 510, 500, 495, 525, 540, 490, 480, 55…
$ treatment <chr> "High_Protein", "Standard", "High_Protein", "Control…
Shows: number of rows, columns, column names, types, and first few values
Structure of object:
str(cattle)spc_tbl_ [20 × 7] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
$ animal_id : chr [1:20] "C001" "C002" "C003" "C004" ...
$ birth_date : Date[1:20], format: "2023-03-15" "2023-03-18" ...
$ breed : chr [1:20] "Angus" "Hereford" "Angus" "Charolais" ...
$ sex : chr [1:20] "M" "F" "M" "F" ...
$ initial_weight_kg: num [1:20] 285 270 290 295 280 275 285 300 278 272 ...
$ final_weight_kg : num [1:20] 520 485 535 510 500 495 525 540 490 480 ...
$ treatment : chr [1:20] "High_Protein" "Standard" "High_Protein" "Control" ...
- attr(*, "spec")=
.. cols(
.. animal_id = col_character(),
.. birth_date = col_date(format = ""),
.. breed = col_character(),
.. sex = col_character(),
.. initial_weight_kg = col_double(),
.. final_weight_kg = col_double(),
.. treatment = col_character()
.. )
- attr(*, "problems")=<externalptr>
More technical, shows object class and internal structure
Statistical summary:
summary(cattle) animal_id birth_date breed sex
Length:20 Min. :2023-03-15 Length:20 Length:20
Class :character 1st Qu.:2023-03-30 Class :character Class :character
Mode :character Median :2023-04-16 Mode :character Mode :character
Mean :2023-04-17
3rd Qu.:2023-05-06
Max. :2023-05-25
initial_weight_kg final_weight_kg treatment
Min. :268.0 Min. :475.0 Length:20
1st Qu.:275.0 1st Qu.:488.8 Class :character
Median :283.5 Median :507.5 Mode :character
Mean :284.5 Mean :510.8
3rd Qu.:292.8 3rd Qu.:531.2
Max. :305.0 Max. :555.0
For numeric columns: min, max, quartiles, mean For character/factor: counts
2.8.2 Dimensions
# Number of rows
nrow(cattle)[1] 20
# Number of columns
ncol(cattle)[1] 7
# Both at once (rows, columns)
dim(cattle)[1] 20 7
2.8.3 Column Names
# Get column names
names(cattle)[1] "animal_id" "birth_date" "breed"
[4] "sex" "initial_weight_kg" "final_weight_kg"
[7] "treatment"
# Or
colnames(cattle)[1] "animal_id" "birth_date" "breed"
[4] "sex" "initial_weight_kg" "final_weight_kg"
[7] "treatment"
2.8.4 Quick Counts
# Count observations by treatment
library(dplyr)
cattle %>% count(treatment)# A tibble: 3 × 2
treatment n
<chr> <int>
1 Control 6
2 High_Protein 8
3 Standard 6
# Count by breed and sex
cattle %>% count(breed, sex)# A tibble: 6 × 3
breed sex n
<chr> <chr> <int>
1 Angus F 3
2 Angus M 6
3 Charolais F 4
4 Charolais M 1
5 Hereford F 3
6 Hereford M 3
2.9 Data Structures: Data Frames vs Tibbles
2.9.1 Data Frames (Base R)
A data frame is R’s traditional way to store tabular data:
- Rows are observations
- Columns are variables
- Columns can be different types (numeric, character, factor)
# Create a basic data frame
df <- data.frame(
id = 1:3,
name = c("Bessie", "Daisy", "Buttercup"),
weight_kg = c(450, 425, 475)
)
class(df)[1] "data.frame"
df id name weight_kg
1 1 Bessie 450
2 2 Daisy 425
3 3 Buttercup 475
2.9.2 Tibbles (Tidyverse)
A tibble is the tidyverse version of a data frame:
library(tibble)
# Create a tibble
tib <- tibble(
id = 1:3,
name = c("Bessie", "Daisy", "Buttercup"),
weight_kg = c(450, 425, 475)
)
class(tib)[1] "tbl_df" "tbl" "data.frame"
tib# A tibble: 3 × 3
id name weight_kg
<int> <chr> <dbl>
1 1 Bessie 450
2 2 Daisy 425
3 3 Buttercup 475
2.9.3 Data Frame vs Tibble
| Feature | Data Frame | Tibble |
|---|---|---|
| Printing | Prints everything | Prints first 10 rows |
| Column types | Shown with str() |
Shown when printing |
| Strings to factors | Yes (old R) | Never |
| Subsetting | Inconsistent | Consistent |
| Modern tidyverse | ❌ | ✅ |
When using tidyverse packages, tibbles are better:
- Better printing (won’t flood your console)
- Better warnings when something goes wrong
- More predictable behavior
- Column types always visible
Convert data frame to tibble:
tib <- as_tibble(df)2.9.4 Vectors
Both data frames and tibbles are built from vectors—the most basic R data structure.
# Numeric vector
weights <- c(250, 275, 300, 285)
weights[1] 250 275 300 285
# Character vector
names <- c("Bessie", "Daisy", "Buttercup", "Moolinda")
names[1] "Bessie" "Daisy" "Buttercup" "Moolinda"
# Logical vector
is_heavy <- weights > 280
is_heavy[1] FALSE FALSE TRUE TRUE
Key point: Each column in a data frame/tibble is a vector!
2.10 The R Help System
Learning to find help is crucial for becoming independent.
2.10.1 Function Help
# Get help for a function
?read_csv
help(read_csv)
# Search for topic
??csv
help.search("csv")2.10.2 Package Help
# Overview of package
help(package = "readr")
# List all functions
library(help = "readr")2.10.3 Vignettes
Vignettes are long-form tutorials:
# See available vignettes
vignette(package = "readr")
# Open a specific vignette
vignette("readr")2.10.4 Examples
Most help files have examples at the bottom:
# Run examples from help file
example(read_csv)2.10.5 Online Resources
When stuck, try:
- Google: “R read csv with missing values”
- Stack Overflow: stackoverflow.com/questions/tagged/r
- Package websites: Often have better documentation than
?function - R for Data Science: https://r4ds.hadley.nz/
When asking questions online:
- Describe what you want to do
- Show your code (formatted!)
- Include error messages (full text)
- Provide example data (use
dput()or built-in datasets) - Say what you’ve tried
Good question = fast, helpful answers!
2.11 Summary
This chapter introduced the R ecosystem for data analysis:
- RStudio interface has four main panes: Source, Console, Environment, Files
- R Projects organize your work and use relative paths for reproducibility
- The
herepackage makes file paths work anywhere - Installing packages (
install.packages()) is done once; loading packages (library()) is done every session - Quarto documents combine code, text, and output for reproducible reports
- YAML headers control document settings; markdown formats text; code chunks execute R code
read_csv()from readr is better thanread.csv()for importing CSV filesread_excel()from readxl imports Excel files- Exploration functions:
head(),tail(),glimpse(),str(),summary(),names(),dim() - Tibbles are better than data frames for tidyverse workflows
- R’s help system:
?function,help(),vignette(), and online resources
2.12 Homework Assignment
2.12.1 Assignment: Import, Explore, and Document Data
Due: Before Week 3
2.12.1.1 Part 1: Project Setup (20 points)
Create a new R Project called
ans500_week2_yournameCreate this folder structure within your project:
data/ raw/ processed/ code/ output/ figures/Download two data files (your instructor will provide links):
cattle_weights.csvfeed_records.xlsx
Place both files in
data/raw/
2.12.1.2 Part 2: Data Import and Exploration (40 points)
Create a Quarto document called week2_homework.qmd that:
- Loads necessary packages (tidyverse, readxl, here)
- Reads both data files using appropriate functions
- Explores the CSV data (cattle_weights.csv):
- Show dimensions (rows and columns)
- Display column names and types
- Show first 10 rows
- Provide a statistical summary
- Count observations by treatment and by breed
- Explores the Excel data (feed_records.xlsx):
- Show dimensions
- Display column names and types
- Show first 8 rows
- Calculate mean feed consumption by feed type
- Documents your observations:
- What variables are in each dataset?
- What do you notice about the data?
- Any missing values or unusual patterns?
- Any potential data quality issues?
2.12.1.3 Part 3: Quarto Skills (40 points)
Your Quarto document must demonstrate:
- Proper YAML header with:
- Title: “Week 2 Homework: Data Import and Exploration”
- Your name as author
- Today’s date
- HTML output with table of contents
- Code folding off
- Markdown formatting:
- Level 2 headers (##) for major sections
- Level 3 headers (###) for subsections
- Use bold and italic for emphasis
- Create a bulleted list
- Code chunks with appropriate options:
- Name at least 3 code chunks
- Use
#| message: falsewhere appropriate - Use
#| echo: trueto show code
- Written interpretation:
- Each analysis section includes 2-3 sentences explaining what the output shows
- Final section (150-200 words) comparing CSV vs Excel import process
Render to HTML and submit both .qmd and .html files.
2.12.2 Recommended YAML
---
title: "Week 2 Homework: Data Import and Exploration"
author: "Your Name"
date: today
format:
html:
toc: true
toc-depth: 3
code-fold: false
theme: cosmo
embed-resources: true
execute:
warning: false
message: false
---2.12.3 Grading Rubric
- Project Setup (20%):
- R Project created properly (5%)
- Folder structure correct (10%)
- Data files in correct location (5%)
- Data Import and Exploration (40%):
- Both files imported correctly (10%)
- All required exploration completed (20%)
- Observations documented (10%)
- Quarto Skills (40%):
- YAML header correct and complete (10%)
- Markdown formatting used effectively (10%)
- Code chunks properly configured (10%)
- Written interpretation clear and complete (10%)
2.12.4 Bonus (5 points)
Create a simple visualization of either dataset using base R plotting:
# Example: Histogram of initial weights
hist(cattle$initial_weight_kg,
main = "Distribution of Initial Cattle Weights",
xlab = "Weight (kg)",
col = "steelblue")2.13 Additional Resources
2.13.1 Required Reading
- R for Data Science (2e) - Chapters 6-8: Workflow, Data Import
- Quarto Tutorial - Complete the “Hello, Quarto” tutorial
2.13.2 Optional Reading
- RStudio IDE Cheat Sheet
- readr documentation
- readxl documentation
- Wickham, H. (2014). “Tidy Data.” Journal of Statistical Software, 59(10). Link
2.13.3 Videos
- “RStudio for the Total Beginner” by RStudio
- “Getting Started with Quarto” by Posit
- “How to Import Data in R” by DataCamp
2.13.4 Cheat Sheets
2.13.5 Useful Websites
- Tidyverse - Homepage for tidyverse packages
- Posit Community - Forum for RStudio/Quarto questions
- Stack Overflow - Q&A for R programming
Next Chapter: Data Types, Strings, and Introduction to dplyr