Block 4: Data frames

Week 2 · Introduction to R · Imai §1.3.5 · about 15 min

NoteHow this works

Read the code and predict (write it down or tell your neighbour), answer the question, then run it with Run Code. Every cell is editable; Start Over resets it. Errors are information: read them.

UNpop.csv is already loaded for you in this page (no working directory needed).

1. Inspect before you analyze

2. Predict: do these three return the same thing?

Read this code (it is not run yet):

UNpop <- read.csv("UNpop.csv")
UNpop$world.pop
UNpop[, "world.pop"]
UNpop[, 2]
Predict: Do UNpop$world.pop, UNpop[, "world.pop"] and UNpop[, 2] return the same thing?
Each picks the second column; selecting one column gives a vector.

Now run it and compare with your answer:

3. Predict: what shape does each return?

A vector or a data frame?

Read this code (it is not run yet):

UNpop <- read.csv("UNpop.csv")
UNpop[c(1, 2, 3), ]
UNpop[1:3, "year"]
class(UNpop[c(1, 2, 3), ])
class(UNpop[1:3, "year"])
Predict: What does UNpop[1:3, "year"] return?
One column gives a vector; UNpop[1:3, ] (several columns) gives a data frame.

Now run it and compare with your answer:

4. Subsetting rows with a condition

5. Your turn

Extract the years for which world population exceeds 5,000,000 (thousands).

# Combine a condition with $year:
# UNpop$year[ <condition on UNpop$world.pop> ]
UNpop <- read.csv("UNpop.csv") UNpop$year[UNpop$world.pop > 5000000] # 1990 2000 2010
UNpop <- read.csv("UNpop.csv")
UNpop$year[UNpop$world.pop > 5000000]    # 1990 2000 2010