4  Start of Computing in R: Install, Project, First Import

NoteData for this chapter

This chapter uses the BC silviculture (bc_disturbance_reforestation.xlsx) and Ontario forest statistics (on_forest_statistics_1.xlsx) workbooks. Click each file name to download it directly, then save it in your data/ folder. For sources and details, see the Datasets Used in This Book page.

Chapter goals

By the end of this chapter you will be able to:

  • Explain the difference between R, RStudio, Quarto, and Posit Cloud, and choose which you will use.
  • Install R and RStudio on your computer, or create a free Posit Cloud account (recommended for getting started).
  • Create an RStudio Project for FRST 232 with a clean folder structure (data/, outputs/, R/, notes/).
  • Install and load the tidyverse, readxl, and here packages.
  • Use the here() function for portable, project-relative file paths.
  • Import the BC silviculture file from Chapter 1 into R using readxl::read_excel().
  • Inspect the imported tibble (R’s tidyverse data table — introduced fully in Chapter 5) with dim(), nrow(), ncol(), names(), glimpse(), summary(), and head().
  • Confirm the numbers R computes match the numbers you computed in Excel in Chapters 1–3.
  • Use the native pipe |> to chain operations.
  • Recognize and read common error messages.

Expected output for this chapter

TipWhat you will hand in
  1. A working RStudio Project named frst232/ (or frst232-yourname/), either on your local machine or on Posit Cloud, with this folder structure:

    frst232/
    ├── frst232.Rproj
    ├── data/bc_disturbance_reforestation.xlsx
    ├── outputs/
    ├── R/
    └── notes/
  2. A rendered Quarto HTML file (frst232_ch04_learner.html) showing the result of importing and inspecting the BC silviculture file. The file should include:

    • the working directory printed by here::here(),
    • dim(bc), names(bc), and glimpse(bc) output,
    • the five basic statistics (sum, mean, min, max, median) of bc$Reforestation_ha,
    • a one-line confirmation that the R numbers match the Excel numbers from Chapter 1.
  3. A short group-lab worksheet (or screenshot) submitted to the course site.

This list is the same as the rubric for the chapter assignment. Keep it in view while you work.

4.1 Why R, why now

For three chapters, every analysis lived inside Excel. You wrote formulas, dragged them across grids, built PivotTables, made charts. Real work.

But you also saw the limits:

  • PivotTable refresh. Change the Data sheet → forget to refresh → silent stale data.
  • Cell-reference shifts. Copy a formula one cell over → forget the $ → silently wrong percentages.
  • Display vs value. Two cells show 100,000 → one is 99999.999. =A1=B1 is FALSE and nobody notices.
  • No history. Six months later, “how did I get this number?” is unanswerable.

R fixes these — not by being smarter, but by making every step a written instruction. The instruction is the audit trail. Run it again, get the same number. Send it to a colleague, get the same number. Edit one line, re-run, see what changed.

Chapter 4 is where the language changes. The data does not. The file you import today is the same bc_disturbance_reforestation.xlsx from Chapter 1. The numbers you compute will be identical. What changes is that the steps are now scriptable.

4.2 R, RStudio, Quarto, Posit Cloud — what each thing is

These four words show up everywhere. They are not the same thing.

Name What it is When you need it
R The computing language and engine. The thing that does the math. Always. R is the underlying tool.
RStudio A friendly editor for R, with a console, file browser, and project manager. Almost always. You could use R without it, but you do not want to.
Quarto A document format that lets you mix R code, R output, and prose into one rendered HTML / PDF / Word file. When you want to write a report (Chapter 5 onward).
Posit Cloud A free, browser-based version of RStudio that runs in the cloud — no install needed. When you do not want to (or cannot) install R locally.
TipThe recommended path for this course

If you have never used R before, start with Posit Cloud. No installation. No version conflicts. Works on any laptop, any operating system, any course-lab computer.

Switch to a local install only if (a) you need to work offline or (b) you are comfortable troubleshooting R installation issues yourself.

4.4 Path B — Install R and RStudio locally

If you prefer (or need) a local install:

4.4.1 Install R

4.4.2 Install RStudio

4.4.3 Install Quarto

4.4.4 Verify

Open RStudio. In the Console pane (bottom-left), type:

R.version.string

You should see something like "R version 4.5.0 (2025-04-11)". If you do, you are ready.

4.5 Creating an RStudio Project

Whether on Posit Cloud or local, always work inside an RStudio Project. Never run R code without a project.

A project is just a folder with a .Rproj file inside it. The .Rproj file tells RStudio:

  • where your working directory is,
  • which files belong to this project,
  • how to keep your R session separate from other projects.
NotePosit Cloud users: you already created your project

If you followed Path A, the New RStudio Project you made in Posit Cloud (Path A, step 3) is your course project — you do not need to create another one. Read this section for the why, then continue at Folder structure. The To create the project steps just below are written for a local (Path B) install.

4.5.1 To create the project

In RStudio: File → New Project → New Directory → New Project.

  • Directory name: frst232
  • Create project as subdirectory of: pick a sensible parent folder (e.g., your Documents/ folder, or — on Posit Cloud — the default).
  • Click Create Project.

RStudio opens a fresh session inside the new folder. The top-right corner of the window now reads frst232.

4.5.2 Why this matters

Without a project, your R session has no anchor. You end up typing absolute paths like /Users/yourname/Desktop/FRST232/Lab1/data.csv — which break the moment you move the folder, switch computers, or share with a classmate.

With a project, you type relative paths like data/bc_disturbance_reforestation.xlsx. R knows the project root and resolves the rest. Portable forever.

4.6 Folder structure (same as Chapters 1–3, now used by R)

Inside your frst232 project folder, create these subfolders. In RStudio, use the Files pane (bottom-right) → New Folder.

frst232/
├── frst232.Rproj                                   ← created automatically
├── data/                                           ← raw input files
│   └── bc_disturbance_reforestation.xlsx
├── outputs/                                        ← cleaned files, figures
├── R/                                              ← reusable R scripts (.R files)
├── notes/                                          ← scribbles, screenshots
└── deliverables/                                   ← what you submit

Same three rules from Chapter 1:

  1. Never edit raw data in place. data/ is read-only.
  2. Use lowercase, snake_case names. No spaces, no capitals.
  3. One folder per chapter (or per topic). Easier to find things later.

4.6.1 Place the BC file

If you do not have it already, download bc_disturbance_reforestation.xlsx from the BC Data Catalogue (https://catalogue.data.gov.bc.ca/dataset/indicator-summary-data-trends-in-silviculture-in-b-c-) and drop it into data/.

On Posit Cloud, you upload files through the Files pane → Upload button.

4.7 Installing packages

R on its own can do a lot, but most real work uses packages — pre-written collections of functions. You install a package once, then load it at the start of every R session that needs it.

The three packages we use this chapter:

Package What it does
tidyverse A bundle of packages for data manipulation, plotting, and reshaping. The backbone of modern R.
readxl Reads .xlsx and .xls files.
here Builds portable, project-relative file paths.

4.7.1 To install

In the RStudio Console, type:

install.packages(c("tidyverse", "readxl", "here"))

Press Enter. This will take a minute or two the first time — R downloads each package and its dependencies.

Warninginstall vs library
  • install.packages(...) — runs once per machine. Downloads and installs.
  • library(...) — runs once per R session. Loads the installed package so its functions are available.

Confusing these two is the most common first-day R bug. “I installed it but R says it can’t find the function” — almost always means you forgot the library() call.

4.7.2 To load

At the top of every R script or Quarto document for this course, include:

library(tidyverse)
library(readxl)
library(here)

4.8 here() — portable paths

The here() function builds a path relative to your project root. Type this in the Console:

here("data", "bc_disturbance_reforestation.xlsx")

You should see a string like:

/cloud/project/data/bc_disturbance_reforestation.xlsx

(or, on a local install, something like /Users/yourname/Documents/frst232/data/bc_disturbance_reforestation.xlsx)

The point: the same code works for everyone. You do not need to know the full path; here() figures it out.

TipWhy this matters for collaboration

When you share your project folder with a classmate (or with a TA for grading), they may unzip it to a completely different location. Because every file path uses here(), the code still works — no edits required.

This is the reproducibility win that pure-Excel work cannot give you.

4.9 Your first R commands

Open a new R script: File → New File → R Script. Save it into R/ as 01_first_import.R.

Type these lines (or copy-paste). Run them one at a time by clicking on the line and pressing Ctrl+Enter (Cmd+Enter on Mac):

# Load packages — run these once at the start of every R session
library(tidyverse)   # dplyr, ggplot2, readr, and friends
library(readxl)      # read_excel() for .xlsx files
library(here)        # here() builds project-relative paths
library(knitr)       # kable() for tidy tables (used later this chapter)
library(scales)      # label_comma() and friends for number formatting

# Import the BC silviculture file (same one you used in Chapter 1)
bc <- read_excel(here("data", "bc_disturbance_reforestation.xlsx"),
                 sheet = "Data")

# Inspect
dim(bc)
names(bc)
glimpse(bc)

What you should see:

dim(bc): 37 8 
names(bc):
[1] "Fiscal_Year"                   "Clearcutting_ha"              
[3] "Clearcutting_with_reserves_ha" "Partial_cutting_ha"           
[5] "Harvested_ha"                  "Natural_Disturbance_ha"       
[7] "Total_Disturbance_ha"          "Reforestation_ha"             

glimpse(bc):
Rows: 37
Columns: 8
$ Fiscal_Year                   <dbl> 1987, 1988, 1989, 1990, 1991, 1992, 1993…
$ Clearcutting_ha               <dbl> 216304.92, 217836.07, 190635.52, 172360.…
$ Clearcutting_with_reserves_ha <dbl> 5800.400, 1842.952, 1456.666, 1400.013, …
$ Partial_cutting_ha            <dbl> 20076.681, 31878.294, 23785.954, 18930.8…
$ Harvested_ha                  <dbl> 242182.0, 251557.3, 215878.1, 192691.6, …
$ Natural_Disturbance_ha        <dbl> 20875.00, 9641.20, 10711.80, 28300.70, 1…
$ Total_Disturbance_ha          <dbl> 263057.0, 261198.5, 226589.9, 220992.3, …
$ Reforestation_ha              <dbl> 201972.5, 221296.3, 237275.9, 260370.8, …

37 rows × 8 columns — exactly the BC file you knew from Chapter 1, now living inside R.

ImportantLoad your packages at the start of every session

library() loads a package for the current session only. Run all five library() lines above before anything else each time you open RStudio or Posit Cloud. In particular, library(tidyverse) does not load knitr or scales — you need those two separate lines, or later examples (kable() in this chapter, label_comma() in Chapter 9) fail with “could not find function”.

4.9.1 Line by line — what each command did

Several new ideas appear at once above. Here is what each line does:

Code What it does
library(tidyverse) Loads the common data-analysis tools (dplyr, ggplot2, …).
library(readxl) Loads the package that can read Excel files.
library(here) Loads here(), which builds paths from the project root.
here("data", "…xlsx") Builds the path from your project folder to the data file.
read_excel(…, sheet = "Data") Reads the Data sheet (not About or ReadMe) into R.
bc <- … Stores the result as a tibble named bc.
dim(bc) Number of rows and columns.
names(bc) The column names.
glimpse(bc) A compact preview of every column’s type and first values.
WarningKeep the workbook as .xlsx — don’t export it to CSV

If you open the workbook in Excel and use File → Export / Save As → CSV, Excel writes only the active sheet — you can end up with bc_disturbance_reforestation(About).csv containing just the About tab. The import needs the Data sheet, so keep the original .xlsx and read it with read_excel(…, sheet = "Data").

4.9.2 The assignment operator <-

You probably noticed the <- symbol. It is the assignment operator“store this on the right into this name on the left”. In R, <- is preferred over = for assignment because = has other uses (function arguments).

A keyboard shortcut: Alt+- (Windows / Linux) or Option+- (Mac) inserts <- with a space.

4.10 The Excel-to-R bridge — side by side

The following table is what Chapters 1, 2, and 3 have been previewing. Now you can actually run the right-hand column.

What you did in Excel What you do in R Result on the BC file
Open the file by double-clicking bc <- read_excel(here("data", "bc_disturbance_reforestation.xlsx"), sheet = "Data") A tibble in memory called bc
Read the status-bar Count nrow(bc) 37
Read the status-bar Sum for column H sum(bc$Reforestation_ha) 8,264,064
Read the status-bar Average for column G mean(bc$Total_Disturbance_ha) 228,089
Scan the Data sheet visually glimpse(bc) and summary(bc) text summaries
=MIN(F2:F38) min(bc$Natural_Disturbance_ha) 1,448
=MAX(F2:F38) max(bc$Natural_Disturbance_ha) 218,275

Every number on the right matches the value you saw in Chapter 1. The data is the same. The columns are the same. The only thing that changed is how you ask for the answer.

4.11 Accessing columns with $

bc$Reforestation_ha means “the column called Reforestation_ha inside the tibble bc”. The $ is the column selector.

Try these in the Console:

bc$Fiscal_Year                  # the year column (37 numbers)
bc$Reforestation_ha             # the reforestation column
sum(bc$Reforestation_ha)        # total reforestation
mean(bc$Reforestation_ha)       # mean annual reforestation
length(bc$Reforestation_ha)     # how many values (= 37)

4.11.1 Tab completion saves typos

In RStudio, after you type bc$, press Tab. A dropdown shows every column name. Click one (or arrow-down + Tab) to insert it. This prevents the “I spelled the column wrong” class of bugs.

4.12 Computing the chapter’s five statistics

sum(bc$Reforestation_ha)
mean(bc$Reforestation_ha)
min(bc$Reforestation_ha)
max(bc$Reforestation_ha)
median(bc$Reforestation_ha)
Statistic Result
Total reforestation 8,264,064 ha
Mean annual reforestation 223,353 ha
Min annual reforestation 189,394 ha
Max annual reforestation 274,616 ha
Median annual reforestation 219,925 ha

Match against Chapter 1. Open bc_silviculture_ch01_workbook.xlsx from your Chapter 1 deliverables and compare. Total reforestation should match to the last decimal. If anything does not match, something is wrong — either with your import or with the file you handed in for Chapter 1.

4.13 The native pipe |>

The pipe operator |> takes the thing on its left and sends it into the first argument of the function on its right. It reads left-to-right, like a sentence.

Without the pipe:

round(mean(bc$Reforestation_ha), 0)

With the pipe:

bc$Reforestation_ha |> mean() |> round(0)

Same answer. The piped version reads top to bottom: “take the reforestation column → take its mean → round to zero decimals”.

This is the same logical pattern as chaining slicers in PivotTables: a sequence of operations applied one after the other. The pipe is how that sequence looks in R.

TipWhen pipes help, when they hurt
  • Pipes help when you have 3 or more steps that read naturally as a sequence. bc |> filter() |> group_by() |> summarise().
  • Pipes hurt when there is only one step. Just write mean(bc$Reforestation_ha) directly.

Use the pipe when it makes the code easier to read. Skip it when it does not.

4.14 Reading error messages

Errors in R look intimidating. They are not.

A typical first-day error — this example is intentional. We misspelled the column name (Refrestation_ha, missing the second “o”) on purpose so you can see what R prints. You do not need to type or run it:

> sum(bc$Refrestation_ha)
Error in `$.tbl_df`(bc, Refrestation_ha) :
  Column `Refrestation_ha` doesn't exist.
Did you mean `Reforestation_ha`?

Two facts from that message:

  1. The error happens in $ — that is the column-selector.
  2. R suggests a fix — “Did you mean Reforestation_ha?”. You misspelled it.

R errors usually tell you where and why. Read every word. The fix is often in the message itself.

4.14.1 A second common error

> library(tidyverse)
Error in library(tidyverse) : there is no package called 'tidyverse'

R is saying “you tried to load a package you haven’t installed”. The fix is install.packages("tidyverse"), then try again.

TipHow to read any R error in 30 seconds
  1. Read the function name in the error (e.g., $, library, read_excel). That tells you where the problem is.
  2. Read the suggested fix if there is one (R is good at this).
  3. Copy-paste the error into your search engine if you cannot solve it. Someone else has had the same problem.
  4. Ask AI with the full error text and the code that caused it. Vague “my code doesn’t work” prompts give vague answers.

4.15 Active learning

4.15.1 Activity 1 — Spot-check the install

In the Console, type:

R.version.string
sessionInfo()

The first line should report your R version (4.5 or newer). The second should list tidyverse, readxl, and here among the loaded packages (after you have run library(...) on each).

4.15.2 Activity 2 — Verify your folder structure

In the Console, type:

list.files(here("data"))

You should see "bc_disturbance_reforestation.xlsx". If you see an empty result, the file is not where you think it is.

4.15.3 Activity 3 — Import and inspect

Run the import code from the Your first R commands section. Then answer in your own words:

  • What is the type of bc? (Hint: class(bc))
  • How many rows does it have?
  • What are the column names?

4.15.4 Activity 4 — Compute and compare

Compute the five statistics from this chapter. Compare each value to the same statistic in your Chapter 1 deliverable workbook. Do they match?

4.15.5 Activity 5 — Write your first pipe

Take this sequence:

round(mean(bc$Total_Disturbance_ha), 0)

Rewrite it as a pipe with three steps. Confirm the answer is the same.

4.16 Practice Demo Lab

ImportantPractice demo only

This is a guided practice lab in the OER book, designed to help you learn the workflow before completing the official lab assignment on Canvas. The Canvas lab is the graded assignment. Use this activity to practice, compare your work with the reference solution, and learn how to write an AI verification prompt.

This demo lab has six parts — work them in order:

  1. Your attempt. Work through the tasks below.

  2. Reference solution. Compare against the worked examples earlier in this chapter (your public reference). The graded Canvas lab has its own private answer key — do not copy demo solutions into a Canvas submission.

  3. Compare your work with the reference. Where did it match? Where did it differ? What caused the difference, and how did you fix it?

  4. Write your own AI verification prompt. Ask an AI to check your reasoning, code, and outputs — not to produce the answer for you.

  5. Model AI verification prompt.

    “I am doing a FRST 232 practice demo lab. My dataset is [file name] (columns [columns]). I attempted [paste your steps or code] and got [paste the output]. Explain what my work does line by line, tell me whether it answers the task, and list the checks I can run to verify it against the chapter’s worked example. Do not give me the final answer.”

  6. Reflection: what changed after checking? In two or three sentences — did your attempt hold up? what did you fix? what will you check first next time?

NoteLab: Set up a working R project together

Work in groups of 3 or 4. Each member follows the same setup steps on their own computer (or in their own Posit Cloud project). Use the lab session to debug together.

Task 1 — Posit Cloud accounts. Every member creates a free Posit Cloud account (if they have not already).

Task 2 — Create the project. Each member creates a project named frst232 and sets up the folder structure from the Folder structure section.

Task 3 — Install packages. Each member runs:

install.packages(c("tidyverse", "readxl", "here"))

While packages install, discuss: what is a package, and why are there so many?

Task 4 — Upload the data file. Each member uploads bc_disturbance_reforestation.xlsx into data/. Confirm with list.files(here("data")).

Task 5 — First import. Each member runs the import code from the chapter. Confirm everyone sees the same dim(bc) output (37 8).

Task 6 — Compute and compare. Each member computes sum(bc$Reforestation_ha). Confirm everyone gets the same number (8,264,064). Now compare this to the Chapter 1 workbook value. They should match.

Task 7 — Submit. Submit a single screenshot showing one group member’s RStudio with the BC file loaded, the column names visible, and the sum() result. Include all group members’ names on the screenshot or in the submission caption.

This lab is designed to fit comfortably inside a single hands-on session.

TipReference solution — download

Open the Chapter 4 reference solution (rendered HTML) — the completed, rendered solution for this demo lab. Open it after your own attempt and use it to check your work.

This is the public practice solution. The graded lab on Canvas has its own private answer key — do not copy this into a Canvas submission.

4.17 Exercises

These are the take-home exercises that go with this chapter.

  1. Compute mean(bc$Harvested_ha) and confirm it equals the same number you computed in Excel for Chapter 1 (Activity 3, the =AVERAGE(...) formula).

  2. Use the pipe to compute the median of Natural_Disturbance_ha, rounded to the nearest hectare.

  3. Use which.max() to find the index of the largest value in bc$Natural_Disturbance_ha. Then use it to find the year of the maximum:

    bc$Fiscal_Year[which.max(bc$Natural_Disturbance_ha)]

    What year does R report? Does it match Chapter 1?

  4. Use summary(bc) and explain in one sentence what each row of the summary shows (Min, 1st Qu, Median, Mean, 3rd Qu, Max).

  5. Save your R/01_first_import.R script. Close the project. Re-open it. Run the whole script again from top to bottom (Code → Run Region → Run All). Confirm everything works without errors.

  6. Open the Ontario file from Chapter 2 the same way:

    ontario <- read_excel(here("data", "on_forest_statistics_1.xlsx"),
                          sheet = "Data")
    dim(ontario)

    How many rows does R report? Does it match Chapter 2?

  7. Optional, harder. Write a tiny R function that takes a numeric vector and returns a named list with mean, median, min, and max. Apply it to bc$Reforestation_ha.

4.18 Optional, advanced

4.18.1 The old pipe %>%

You may see %>% (the magrittr pipe) in older R code. It does almost the same thing as the native |> but is not built into base R. This course uses the native |> because it is now part of R itself (since R 4.1) and does not require a package.

If you see %>% in a tutorial, treat it as equivalent to |> for most purposes. The differences are minor and only matter in advanced cases.

4.18.2 RStudio Project options

In the project menu (top-right of RStudio), choose Project Options → General. Recommended settings for this course:

  • Restore .RData into workspace on startup: No
  • Save workspace to .RData on exit: Never

These two changes guarantee that your R session starts fresh every time. This sounds inconvenient but is the right discipline: if your code only works because of leftover variables from yesterday, your code is broken.

4.18.3 Reading multiple sheets at once

readxl::excel_sheets() returns the sheet names of a file:

excel_sheets(here("data", "bc_disturbance_reforestation.xlsx"))

You can then purrr::map() over them to read all sheets. We will get to purrr later in the course; just know that batch-import is possible.

4.19 A glimpse ahead: From Excel to Quarto

In Chapter 5 you will write your first Quarto document. Quarto mixes:

  • prose (written in Markdown),
  • R code (in chunks like ```{r} ... ```), and
  • the output of that R code (numbers, tables, charts)

…into one rendered HTML, PDF, or Word file. The chapter you are reading right now is a Quarto document.

In Excel (Ch 1–3) In Quarto (Ch 5+)
Submit a .xlsx workbook Submit a rendered .html (or .pdf) file
Charts as PNG inserts Charts as code chunks that re-render
Cleaning log on a separate sheet Cleaning log as Markdown next to the code
Hand-edited values inside cells Code-computed values that update on re-render
File is the deliverable The .qmd source AND the rendered file together

The principle is the same as Excel’s About / ReadMe / Data pattern: documentation lives with the data. The difference is that the documentation, the code, and the output are now one file.

4.20 Self-assessment quiz

Click the answer you think is correct. The right answer turns green; wrong answers turn red and the correct one is revealed. Explanations appear below each question.

1. What is the difference between R and RStudio?
  • They are the same thing
  • R is the language and engine that runs the math; RStudio is a friendly editor that uses R
  • R is the editor; RStudio is the language
  • RStudio is an older version of R
R does the computation. RStudio is the interface that lets you write, run, and organize R code more easily.
2. Why is it recommended to always work inside an RStudio Project?
  • RStudio refuses to run code without one
  • A project sets the working directory automatically, so relative paths (like data/file.xlsx) work for anyone who opens the project
  • Projects make R faster
  • Projects encrypt your code
The Project anchor lets you use portable file paths. Without it, you end up with absolute paths that break when the folder moves.
3. install.packages("tidyverse") needs to be run —
  • At the top of every R script, every time
  • Once per machine (the package downloads and installs)
  • Never — tidyverse is built into R
  • Only on Mondays
Install is a one-time download. Loading the package (library()) is what you do every session.
4. library(tidyverse) needs to be run —
  • Once per machine
  • Once per R session (at the top of every script that uses tidyverse functions)
  • Never if you have already installed it
  • Only inside an RStudio Project
Loading a package is per-session. R forgets which packages are loaded when you restart it.
5. What does here("data", "bc_disturbance_reforestation.xlsx") return?
  • The contents of the file
  • The absolute path to the file, computed relative to the RStudio Project root
  • An error message
  • The file's modification date
here() builds a portable path. The result is an absolute path string that points to the file regardless of where the project lives on disk.
6. Posit Cloud is —
  • A paid alternative to R
  • A free, browser-based RStudio environment that runs in the cloud — no local install needed
  • A statistics textbook
  • An Excel competitor
Posit Cloud is RStudio running in your browser. Recommended for getting started with R because it avoids installation headaches.
7. The function read_excel() comes from which package?
  • tidyverse
  • readxl
  • here
  • base R
readxl is the tidyverse-adjacent package for reading .xlsx and .xls files. It is not loaded by library(tidyverse) — you need library(readxl) separately.
8. After loading the BC file with bc <- read_excel(...), how do you access just the Reforestation_ha column?
  • bc["Reforestation_ha"]
  • bc$Reforestation_ha
  • Reforestation_ha
  • bc.Reforestation_ha
The $ is the column selector. Tab completion after bc$ shows you every column name.
9. dim(bc) returns c(37, 8). What does that mean?
  • 37 columns and 8 rows
  • 37 rows and 8 columns
  • 37 sheets and 8 files
  • 37 megabytes and 8 packages
dim() returns rows first, then columns. Use nrow() or ncol() if you only want one of them.
10. You ran sum(bc$Reforestation_ha) in R and got a value. In Excel last chapter you also computed total reforestation. The two numbers should be —
  • Different — R rounds differently
  • Identical — same data, same computation, same answer
  • Off by 10%
  • It depends on the day
Whole point of the Excel-to-R bridge: the data did not change, the operation did not change, so the answer cannot change. If they differ, something is wrong.
11. The native pipe in R is —
  • %>%
  • |>
  • ->>
  • ==>
|> is the native pipe, built into R 4.1+. %>% is the older magrittr pipe, which still works but requires a package.
12. x |> mean() is equivalent to —
  • x + mean()
  • mean(x)
  • mean(mean(x))
  • x * mean
The pipe takes the thing on its left and inserts it as the first argument of the function on its right. Useful when chaining several operations.
13. You see this error: Error in library(tidyverse) : there is no package called 'tidyverse'. What do you do?
  • Reinstall R
  • Run install.packages("tidyverse") first, then library(tidyverse)
  • Switch operating systems
  • Ignore it
R is telling you the package was never installed on this machine. Install once, then load. The error message itself names the package — read every word.
14. Inside an RStudio Project, the working directory is —
  • Your Desktop
  • The project root folder (where the .Rproj file lives)
  • /tmp/
  • Wherever you ran the install
The Project anchors the working directory. here() uses this anchor to resolve relative paths.
15. Where should the raw bc_disturbance_reforestation.xlsx file live inside your RStudio Project?
  • In the project root
  • In data/
  • In outputs/
  • On your Desktop
Same folder structure as Chapter 1: raw files in data/, generated files in outputs/, scripts in R/, deliverables in deliverables/.
16. Which is the assignment operator preferred in this course?
  • =
  • <-
  • ::
  • ==
<- is the conventional R assignment operator. = works in most cases but is also used for function arguments, so <- keeps the two uses visually distinct. The keyboard shortcut is Alt+- (Windows) / Option+- (Mac).
17. glimpse(bc) shows you —
  • A pie chart of the data
  • A compact summary of every column with its type and the first few values
  • Only the row count
  • Only the column names
glimpse() is one of the most useful first-look functions. It shows every column, its type, and a preview of the values — like a richer version of Excel's status bar.
18. The five basic statistics from this chapter are —
  • add, subtract, multiply, divide, exponent
  • sum, mean, min, max, median
  • x, y, z, w, v
  • SUMIF, COUNTIF, AVERAGEIF, MAXIF, MINIF
Five base R functions — sum(), mean(), min(), max(), median() — directly equivalent to Excel's SUM, AVERAGE, MIN, MAX, MEDIAN.
19. Which is true about R errors?
  • They are random and impossible to read
  • They usually tell you where the problem is (which function) and often suggest a fix
  • You should always reinstall R when you see one
  • They mean your computer is broken
R errors are written by people for people. Read every word. Often the fix is in the message ("Did you mean ..."), and copy-pasting the error into a search engine usually finds someone with the same problem.
20. Reflection. Describe one moment from this chapter where R felt easier than Excel — or harder. What made the difference?
Common reflections: easier — being able to re-run the whole import in one click instead of clicking through Excel menus · harder — remembering install vs library the first time · easier — typing sum(bc$Reforestation_ha) and getting the same number as my Excel formula, instantly · harder — getting used to writing code instead of clicking · aha moment — realizing the data is the same, just the language is different.

4.21 AI as a debugging companion

TipUseful prompts for this chapter
  • “I am brand new to R. I just installed it and I’m seeing this error message when I run library(tidyverse). What does it mean?” (paste the full error)

  • “Explain step by step what this R code does: bc |> filter(Fiscal_Year >= 2010) |> summarise(total = sum(Reforestation_ha))

  • “I’m getting Error in$.tbl_df(bc, Refrestation_ha). The column name in my Excel file is Reforestation_ha. What’s wrong and how do I fix it?”

4.21.1 Verifying AI’s answers

After AI suggests a fix, check:

  1. Does the fix run without error in your console?
  2. Does the resulting number match what you expect from Chapter 1?
  3. Did AI invent a function that doesn’t exist? (Run ?function_name — if the help page doesn’t open, the function is fictional.)

AI’s R suggestions are usually correct but occasionally include non-existent functions (called “hallucinations”). The two-second check is to look up the function in R’s own help.

4.21.2 When not to use AI

  • Do not paste an exercise question into AI and copy the answer back. The point of the exercise is the thinking.
  • Do not let AI make code-style decisions for you (pipe vs nested, snake_case vs camelCase) without understanding why.
  • Do not let AI invent a replacement for here() that uses absolute paths. Portable paths are non-negotiable for this course.

4.22 Reading

Instructor notes

  • Chapter 4 is structurally different from Chapters 1–3. The first half is installation and setup, which can swallow an entire lab session if your group is mostly new to R.
  • The Excel-to-R bridge table in the Side by side section is the single most important content in this chapter. If learners only remember one thing, it should be that the numbers they computed in Excel are the same numbers R computes, using different syntax for the same data.
  • The old pipe %>% is briefly mentioned in Optional, advanced. Keep the main path on the native |> only — the difference rarely matters for beginners, and consistency makes the course easier to teach.

4.22.1 Posit Cloud vs local install

  • Strongly recommend Posit Cloud for the first lab. It eliminates 90% of “my install isn’t working” tickets.
  • Learners can switch to a local install later in the term once they are comfortable with the workflow.
  • For the lab session, have one TA ready to help with local installs and another with Posit Cloud account creation.

4.22.2 Expected output checklist (matches the top-of-chapter callout)

  1. RStudio Project named frst232/ with the correct folder structure (verify with list.files(here("data"))).
  2. Rendered Quarto HTML showing dim(bc), names(bc), glimpse(bc), and the five basic statistics.
  3. Group-lab worksheet or screenshot.

4.22.3 Materials provided alongside this chapter

File Purpose
bc_disturbance_reforestation.xlsx Raw BC silviculture workbook (carried forward from Chapter 1).
frst232_ch04_learner.qmd Quarto document with TODO chunks for learners to complete.
frst232_ch04_solutions.qmd Completed Quarto document with all code chunks filled in. Do not distribute to learners.
frst232_ch04_starter.zip A pre-built starter project containing the .Rproj file, folder structure, learner .qmd, and a placeholder data folder.
quiz_ch04.html Standalone interactive quiz. Embedded in the rendered chapter; can also be hosted separately.

4.22.4 Suggested facilitation guidance for the Practice Demo Lab

These are optional facilitation and feedback suggestions for instructors running this book demo — not a grading key. The percentages below are relative emphasis, not Canvas marks; the graded lab assignment is on Canvas.

Task Weight What to look for
Posit Cloud accounts (Task 1) 10 % Everyone has an account.
Project + folders (Task 2) 20 % All four folders present; project named correctly.
Packages installed (Task 3) 15 % No load errors for tidyverse, readxl, here.
Data file uploaded (Task 4) 15 % list.files(here("data")) returns the .xlsx name.
Successful import (Task 5) 15 % dim(bc) returns 37 8.
Sum matches Excel (Task 6) 15 % sum(bc$Reforestation_ha) matches the Chapter 1 deliverable to the cent.
Screenshot submission (Task 7) 10 % Screenshot legible; all group members named.

4.22.5 Common stumbling points

  • install vs library confusion. Walk through the distinction explicitly at the start of the lab.
  • Forgot to load readxl. read_excel() errors with “could not find function” if readxl is not loaded.
  • Wrong working directory. Learners who skip the RStudio Project step end up with absolute paths that work on their machine but break in submission. Insist on here() from day one.
  • Misspelled column names. R is case-sensitive. bc$Refor is not bc$Reforestation_ha. Tab completion fixes most of these.
  • The “saved workspace” trap. RStudio’s default is to save your workspace on exit and restore it on startup. This means yesterday’s variables are still around — until they aren’t, and your code mysteriously breaks. Recommend the No / Never setting from Optional, advanced.
  • Excel-to-R bridge: Refer back to the side-by-side table often. When a learner asks “is this the same as the Excel formula?”, the answer is always “yes — here’s the row in the bridge table.”