Block 3: Functions

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

1. Predict: mean() and seq()

Does sum(x) / length(x) give the same as mean(x)? Does the order of named arguments matter in seq()?

Read this code (it is not run yet):

world.pop <- c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
mean(world.pop)
sum(world.pop) / length(world.pop)

seq(from = 1950, to = 2010, by = 10)
seq(to = 2010, by = 10, from = 1950)
seq(from = 2010, to = 1950, by = -10)
2008:2012
2012:2008
Predict: Does sum(x) / length(x) equal mean(x)? Does the order of named arguments in seq() matter?
mean() is exactly sum divided by length. Named arguments are matched by name, so their order is irrelevant (unnamed ones are matched by position).

Now run it and compare with your answer:

Change it: what does seq(1950, 2010, 10) give (no names)? And seq(10, 1950, 2010)?

2. Read, then run: my.summary()

Read the code first. What will the output look like? Then run it.

Read this code (it is not run yet):

my.summary <- function(x) {
  s.out <- sum(x)
  l.out <- length(x)
  m.out <- s.out / l.out
  out <- c(s.out, l.out, m.out)
  names(out) <- c("sum", "length", "mean")
  return(out)
}
z <- 1:10
my.summary(z)
my.summary(world.pop)
Predict: What does my.summary(1:10) return?
The function returns out, a vector with three values and the names set by names(out).

Now run it and compare with your answer:

Change it: s.out was created inside the function. Type s.out on a new last line. What happens, and why?

3. Your turn: write pct.change(x)

Repeat your Block 2 calculation for any vector: the percent change between neighbouring elements. Fill in the function and test it on world.pop.

# Block 2 did it by hand:
# (world.pop[-1] - world.pop[-7]) / world.pop[-7] * 100
# Replace the hard-coded 7 with the length of x.
pct.change <- function(x) { n <- length(x) (x[-1] - x[-n]) / x[-n] * 100 } round(pct.change(world.pop), 1)
pct.change <- function(x) {
  n <- length(x)
  (x[-1] - x[-n]) / x[-n] * 100
}

round(pct.change(world.pop), 1)

Expected: 19.8 22.0 20.5 19.6 15.2 12.9, the same as your Block 2 result. Then try pct.change(c(100, 110, 121)).