1Objectives¶
By the end of this lesson you will be able to:
Load a dataset that ships built in with R or a package.
Import a CSV file with
read.csv(), using the working-directory ideas from L03.Import an Excel file with
readxl::read_excel().Import data directly from a URL, with no download step.
Apply the
mosaicformula interface immediately to whatever you just imported.
2Four ways data arrives, one goal¶
Whatever the source, importing data always ends at the same place: a data
frame in R’s memory (the table you inspected with str() in
L04) that you can then summarize, plot, and test. This lesson
walks through the four shapes data shows up in during this course — built
in, CSV, Excel, and a live URL — because the destination is identical
every time.
31. Built-in data: already in R, no import step at all¶
Some data needs no importing because it ships inside R itself or inside
a package you’ve already loaded. You met this in L01 with
faithful:
head(faithful, 3)
nrow(faithful) eruptions waiting
1 3.600 79
2 1.800 54
3 3.333 74
[1] 272faithful is simply there the moment R starts — no read function of any
kind, because base R ships a small library of teaching datasets with it.
mosaicData (installed alongside mosaic) adds many more, real,
documented datasets the same way. RailTrail — daily bike-trail usage and
weather — becomes available the instant library(mosaic) runs:
str(RailTrail)'data.frame': 90 obs. of 11 variables:
$ hightemp : int 83 73 74 95 44 69 66 66 80 79 ...
$ lowtemp : int 50 49 52 61 52 54 39 38 55 45 ...
$ avgtemp : num 66.5 61 63 78 48 61.5 52.5 52 67.5 62 ...
$ spring : int 0 0 1 0 1 1 1 1 0 0 ...
$ summer : int 1 1 0 1 0 0 0 0 1 1 ...
$ fall : int 0 0 0 0 0 0 0 0 0 0 ...
$ cloudcover: num 7.6 6.3 7.5 2.6 10 ...
$ precip : num 0 0.29 0.32 0 0.14 ...
$ volume : int 501 419 397 385 200 375 417 629 533 547 ...
$ weekday : logi TRUE TRUE TRUE FALSE TRUE TRUE ...
$ dayType : chr "weekday" "weekday" "weekday" "weekend" ...Every built-in dataset has a help page — ?RailTrail or ?faithful — that
documents exactly where the data came from and what each column means. Check
it the moment you meet a new built-in dataset; this book does the same for
every dataset it uses.
42. CSV files: the format you’ll use most¶
A CSV (“comma-separated values”) is a plain-text table — the most common
format for datasets you download, export from a survey tool, or receive from
an instructor. You’ve already used read.csv() since L04; the
piece worth re-emphasizing here is L03’s working-directory rule.
Check what’s actually in your data/ folder before you try to read from it:
list.files("data")[1] "make_survey_sim.R" "survey_sim.csv" Then read it — a relative path, exactly as L03 recommends:
survey <- read.csv("data/survey_sim.csv")
dim(survey)[1] 120 9That’s the full pattern for every CSV this course hands you: confirm the
file is where you think it is, then read.csv("relative/path/to/file.csv").
53. Excel files: one extra package, one extra function¶
R does not read .xlsx files out of the box — you need one small add-on
package, readxl. This is the one
exception to the course’s “just mosaic and BSDA” rule (see
L05): reading someone else’s spreadsheet is
a general R-literacy skill, not a graded statistical method, so readxl is
fine to reach for whenever a dataset arrives as .xlsx instead of .csv.
Nothing about the statistics changes — after read_excel() finishes, you
have an ordinary data frame, same as read.csv() produces.
install.packages("readxl") # once per computer, like mosaic/BSDA
library(readxl)An Excel workbook can hold multiple sheets, so read_excel() needs to
know which one you want. excel_sheets() lists them first:
xlsx_path <- "path/to/workbook.xlsx"
excel_sheets(xlsx_path)[1] "mtcars" "chickwts" "quakes" (This example workbook ships inside the readxl package itself, as
sample data for its own documentation — found via
readxl_example("datasets.xlsx") — so you can run this exact code the
moment readxl is installed, with no download.)
mtcars_xl <- read_excel(xlsx_path, sheet = "mtcars")
head(mtcars_xl, 3)
dim(mtcars_xl)# A tibble: 3 × 11
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
[1] 32 11Two small differences from read.csv(), both harmless: read_excel()
prints as a tibble (# A tibble: 3 × 11, a mosaic/tidyverse-friendly
data frame variant with the same rows-and-columns idea you already know) and
shows each column’s type in a header row (<dbl> = numeric). Everything you
learned about data frames in L04 — $, nrow(), favstats(),
gf_* — works on it identically.
64. Straight from a URL: no download step¶
read.csv() (and read_excel(), given a local copy) can take a web
address instead of a local file path — R fetches the file over the
internet and reads it in, in one step:
penguins_url <- "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
penguins <- read.csv(penguins_url)
dim(penguins)
head(penguins, 3)[1] 344 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18.0 195 3250
sex year
1 male 2007
2 female 2007
3 female 2007This is the real Palmer Penguins dataset (Gorman, Williams & Fraser, 2014; distributed CC0 by Allison Horst and coauthors), fetched live and read directly — 344 rows, 8 columns, no file ever saved to your computer.
75. The formula interface, immediately, on whatever you imported¶
Here’s the payoff for treating “import” as one destination regardless of
source: the instant you have a data frame — from faithful, a CSV, an
Excel sheet, or a URL — the same mosaic formula pattern from
L05 works on it, no matter where it came from:
favstats(~ sleep_hours, data = survey) # from the CSV
favstats(bill_length_mm ~ species, data = penguins) # from the URL min Q1 median Q3 max mean sd n missing
3.9 6.1 6.8 7.425 9.1 6.7875 1.012241 120 0
species min Q1 median Q3 max mean sd n missing
1 Adelie 32.1 36.75 38.80 40.750 46.0 38.79139 2.663405 151 1
2 Chinstrap 40.9 46.35 49.55 51.075 58.0 48.83382 3.339256 68 0
3 Gentoo 40.9 45.30 47.30 49.550 59.6 47.50488 3.081857 123 1favstats(bill_length_mm ~ species, data = penguins) reads exactly the way
L05 taught you — “bill length, broken down by species” —
applied without a single change to a dataset you’d never seen a minute ago.
That reusability is the entire reason mosaic’s formula grammar is worth
learning well: once it’s automatic, a brand-new dataset is never a barrier,
only the statistics is.
8The data/ folder this book uses¶
Every code example in this book that reads a local file uses the same layout, matching what a JupyterHub lab folder or an RStudio Project (see L03) looks like:
r-help/
├── L06.md (this lesson, and the others)
└── data/
├── survey_sim.csv
└── make_survey_sim.RIf you’re following along outside this book’s own project folder, create a
data/ subfolder next to your script or notebook and put the file there —
then read.csv("data/survey_sim.csv") (a relative path, per
L03) resolves correctly on your computer, a classmate’s, or the
CSUB JupyterHub, without any editing.
9Summary¶
Built-in datasets (
faithful, or a package’s likeRailTrail) need no import step — they exist the moment R (or the package) loads.read.csv("data/file.csv")is the everyday tool for CSV files; checklist.files("data")first if you’re not sure a file is where you think.Excel files need one extra package,
readxl;excel_sheets()lists a workbook’s sheets,read_excel(path, sheet = "name")reads one.read.csv("https://...")(andread_excel()on a local copy of a downloaded file) import straight from a URL — but that requires internet on every run, so download-once-and-reuse is safer for repeated work.Whatever the source, the destination is always a data frame — and the
mosaicformula interface (goal( y ~ x, data = ), L05) works on it immediately, with no extra setup.