Block 2: Vectors and indexing

Week 2 · Introduction to R · Imai §1.3.3 · about 18 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.

World population in thousands, 1950–2010 (UN data).

1. Create a vector

2. Predict: indexing

Which elements do these return? Write down your guess, then run.

Read this code (it is not run yet):

world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
world.pop[2]
world.pop[c(2, 4)]
world.pop[c(4, 2)]
world.pop[-3]
Predict: What does world.pop[c(4, 2)] return?
Indexing returns elements in the order you ask for them.

Now run it and compare with your answer:

3. Predict: arithmetic on vectors

What are the first and last element of pop.rate?

Read this code (it is not run yet):

world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
pop.million <- world.pop / 1000
pop.rate    <- world.pop / world.pop[1]
pop.million
pop.rate
Predict: What are the first and last element of pop.rate <- world.pop / world.pop[1]?
Dividing by the first element gives 1 for 1950 and 6916183 / 2525779 ≈ 2.74 for 2010: the population almost tripled.

Now run it and compare with your answer:

4. Predict: growth between decades

How long is pop.increase? Why do we drop the first element in one vector and the last in the other?

Read this code (it is not run yet):

world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
pop.increase     <- world.pop[-1] - world.pop[-7]
percent.increase <- pop.increase / world.pop[-7] * 100
length(pop.increase)
percent.increase
Predict: How long is pop.increase <- world.pop[-1] - world.pop[-7]?
Seven values give six changes. [-1] drops the first, [-7] the last, so each value is lined up with the previous one.

Now run it and compare with your answer:

5. Your turn

In which decade was the percent increase largest? What pattern do you see after 1970?

# which.max() returns the POSITION of the largest element.
# Position 1 is the decade 1950-1960.
world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183) pop.increase <- world.pop[-1] - world.pop[-7] percent.increase <- pop.increase / world.pop[-7] * 100 which.max(percent.increase) # position 2 = the 1960s round(percent.increase, 1) # growth peaks at 22% and then slows down
world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
pop.increase     <- world.pop[-1] - world.pop[-7]
percent.increase <- pop.increase / world.pop[-7] * 100

which.max(percent.increase)    # position 2 = the 1960s
round(percent.increase, 1)     # growth peaks at 22% and then slows down