Data structures for data science
Imagine you collect University ID number and major from 5 friends:
Conceptually, in what ways is the data in these two vectors similar? In what ways is it different?
Imagine instead you asked 100 friends. For each vector, can you think of a more efficient way for the computer to store that data?
Factors
Data Frames
Imagine you collect University ID number and major from 5 friends:
Conceptually, in what ways is the data in these two vectors similar? In what ways is it different?
Imagine instead you asked 100 friends. For each vector, can you think of a more efficient way for the computer to store that data?
A data structure for storing categorical data.
Created with factor().
Stores the values in an integer vector and adds a levels attribute to map integers to character strings.
[1] STAT ECON STAT DATA ECON
Levels: DATA ECON STAT
Objects built on top of simpler data structures can have attributes. A factor’s attributes include its class and levels.
Quickly change all of the values with a particular level.
[1] STATISTICS ECON STATISTICS DATA ECON
Levels: DATA ECON STATISTICS
Add a level even if it’s not observed.
Certain functions behaved differently depending on the class of the object that is passed to it.
You can create a factor with ordered levels by adding ordered = TRUE.
[1] STAT ECON STAT DATA ECON
Levels: STAT < ECON < DATA < BIO
Both are augmented versions of atomic vectors that are given classes to allow for special behavior.
Question: What is the gender and height of the second individual?
😬 This is brittle!
[,1] [,2] [,3]
[1,] "Leia" "1" "150"
[2,] "Luke" "2" "170"
[3,] "Han" "2" "180"
female male
1 2
🤯 Too complicated to subset.
A data frame is a named list of vectors of the same length. Created with data.frame().
name gender height weight
1 Anakin male 1.88 84
2 Padme female 1.65 45
3 Luke male 1.70 77
4 Leia female 1.50 49
A data frame holds attributes for (column) names, row.names, and its class, "data.frame".
colnames(): equivalent to names()rownames(): equivalent to row.names()summary(): summary of each columnstr(): structurehead(): first n rowstail(): last n rowsdim(): dimensionsncol(): number of columnsnrow(): number of rows name gender height weight
1 Anakin male 1.88 84
2 Padme female 1.65 45
3 Luke male 1.70 77
4 Leia female 1.50 49
Using what you know about matrix and list subsetting, write code to subset from star_wars …
height and weight.gender.1.8802:30
Data frames can be subset in 2 ways:
dat[row, col]dat[row, ]dat[ ,col]dat[]dat[[]]dat$



An updated version of a data frame with convenient behaviors.
The main difference is that tibbles are lazy and surly: they do less and complain more.
Hadley Wickham
