2  R in one chapter

Every computation in this book is written in R. This chapter gives a reader who has not used R the part of the language the later chapters rely on. It does not try to cover R as a whole. It covers how to install it, how to keep the work of a survey in one folder, and how to read, transform, summarize and plot a table. The examples use the frame of The Gambia and the 2019-20 DHS report that the book plans from, so the chapter already speaks of EAs, LGAs and households.

A reader who already writes R with dplyr can go straight to Chapter 3, which introduces svyplan and samplyr.

2.1 Installing R and an editor

R is free and runs on Windows, macOS and Linux. Download it from the Comprehensive R Archive Network (CRAN), at https://cran.r-project.org, and install it like any other program. R itself is a console, a window where commands are typed and answered. Most users work in an editor built around it. RStudio and Positron, both from Posit, are the common choices. Each shows a script, the console, the objects in memory and the plots in one window.

R grows through packages, collections of functions written by other users. The book uses five of them for the design and its estimates, and two for data and graphics. They are installed once, from CRAN, with install.packages().

install.packages(c("svyplan", "samplyr", "sondage", "decoupage",
                   "survey", "dplyr", "ggplot2"))

A package installed is not yet loaded. library() loads it into the session, and a script loads the packages it needs at its top. This chapter needs two.

library(dplyr)
library(ggplot2)

2.2 A project for each survey

A survey’s design work produces scripts, frames, tables from the last report and outputs. Keep them in one folder, a project, with the data in a subfolder. The book’s own folder has this layout, with the frames and the report tables in data/ and shared helpers in R/.

Write the commands in a script, a plain text file ending in .R, rather than typing them in the console. A script is a record of the design. It can be rerun when the frame changes, reviewed by a colleague, and attached to the sample design report. In RStudio and Positron, a line of a script is sent to the console with Ctrl+Enter, and the whole script with Ctrl+Shift+Enter (Cmd in place of Ctrl on a Mac).

R reads and writes files relative to its working directory. When an editor opens a project, the working directory is the project folder, so a path such as data/gmb24_eas.rds finds the frame wherever the folder sits on the disk. getwd() prints the working directory. Avoid writing full paths such as C:/Users/... in a script, since they break on any other computer.

2.3 Objects and vectors

R works with objects. The arrow <- stores a value under a name, and typing the name prints the value.

take <- 25
take
#> [1] 25
take * 12
#> [1] 300

The simplest objects are vectors, sequences of values of one type. c() combines values into a vector. A numeric vector holds numbers, a character vector holds text between quotes, and a logical vector holds TRUE or FALSE.

lga <- c("Banjul", "Kanifing", "Brikama", "Mansakonko")
selected <- c(1000, 1150, 1250, 675)
completed <- c(0.905, 0.893, 0.951, 0.967)
selected * completed
#> [1]  905.000 1026.950 1188.750  652.725
selected > 1000
#> [1] FALSE  TRUE  TRUE FALSE

Arithmetic applies to every element at once. The product above gives the households interviewed in each of the four LGAs, without a loop. A comparison gives a logical vector, one value per element.

Square brackets select elements, by position, by a logical vector, or by name.

lga[2]
#> [1] "Kanifing"
lga[selected > 1000]
#> [1] "Kanifing" "Brikama"
names(selected) <- lga
selected["Brikama"]
#> Brikama 
#>    1250

A value that is not known is written NA, for “not available”. It spreads through arithmetic, since the sum of a known and an unknown number is unknown. Functions that summarize a vector take na.rm = TRUE to leave the missing values out.

eas_2019 <- c(40, 46, NA, 27)
sum(eas_2019)
#> [1] NA
sum(eas_2019, na.rm = TRUE)
#> [1] 113
is.na(eas_2019)
#> [1] FALSE FALSE  TRUE FALSE

A missing value in a frame, such as a household count that was never entered, is a question for the planner before it is one for R. The book checks frames for them in Chapter 5.

2.4 Functions and help

A function takes arguments in parentheses and returns a value. Arguments are matched by position or by name, and a named argument can be given in any order. Many arguments have a default and can be left out.

round(0.12345, digits = 2)
#> [1] 0.12
round(digits = 2, 0.12345)
#> [1] 0.12
round(0.12345)
#> [1] 0

Every function of R and of its packages has a help page, which lists its arguments, explains them and ends with examples. ?round opens it. The help pages of svyplan and samplyr are the reference for every function the book uses, and the book does not repeat them.

?round
help(package = "samplyr")

When two packages export a function of the same name, the one loaded last wins. dplyr::filter() names the package explicitly. The helpers of this book use that form, as in samplyr::draw(), so that they work whatever packages are loaded.

2.5 Data frames

A data frame is a table, a set of vectors of the same length, one per column. Survey frames and report tables are data frames. read.csv() reads a comma-separated file, the format in which this book stores the tables it transcribed from reports.

inputs <- read.csv("data/gmb_dhs2019_lga.csv")
head(inputs, 3)
#>        lga eas_urban eas_rural women_expected selected completed
#> 1   Banjul        40         0           1567     1000     0.905
#> 2 Kanifing        46         0           1804     1150     0.893
#> 3  Brikama        46         4           2015     1250     0.951
#>     hrr women women_rr  mcpr mcpr_se mcpr_deft married mcpr_rse
#> 1 0.947  1021    0.928 0.217   0.019     1.016     494    0.087
#> 2 0.934  1743    0.925 0.159   0.016     1.246     854    0.098
#> 3 0.975  2470    0.953 0.197   0.012     1.086    1391    0.059
#>    vacc vacc_deft children
#> 1 0.769     1.148       75
#> 2 0.789     1.373      138
#> 3 0.845     1.096      276

Each row is an LGA, and each column a quantity of the 2019-20 report. selected counts the households selected and completed the share of them interviewed. nrow(), ncol() and names() describe the table, and $ extracts one column as a vector.

nrow(inputs)
#> [1] 8
names(inputs)
#>  [1] "lga"            "eas_urban"      "eas_rural"     
#>  [4] "women_expected" "selected"       "completed"     
#>  [7] "hrr"            "women"          "women_rr"      
#> [10] "mcpr"           "mcpr_se"        "mcpr_deft"     
#> [13] "married"        "mcpr_rse"       "vacc"          
#> [16] "vacc_deft"      "children"
inputs$mcpr
#> [1] 0.217 0.159 0.197 0.144 0.208 0.141 0.182 0.078
mean(inputs$mcpr)
#> [1] 0.16575

R also has its own file format. saveRDS() writes any object to a .rds file, and readRDS() reads it back unchanged, with the types of its columns. The frame of The Gambia is stored that way, one row per EA.

eas <- readRDS("data/gmb24_eas.rds")
str(eas)
#> 'data.frame':    5054 obs. of  6 variables:
#>  $ ea_id      : chr  "1021001" "1021002" "1021003" "1021004" ...
#>  $ lga        : chr  "Banjul" "Banjul" "Banjul" "Banjul" ...
#>  $ district   : chr  "Banjul Central" "Banjul Central" "Banjul Central" "Banjul Central" ...
#>  $ ward       : chr  "New Town East" "New Town East" "New Town East" "New Town East" ...
#>  $ urban_rural: chr  "Urban" "Urban" "Urban" "Urban" ...
#>  $ households : int  81 55 91 94 91 50 68 99 107 55 ...

str() shows the structure of an object, here 5,054 EAs, each with its code, its LGA, district and ward, whether it is urban or rural, and its number of households. Files from Stata, SPSS or Excel are read by the haven and readxl packages, into the same kind of table.

A tibble is a data frame that prints more compactly, showing only the first rows and the type of each column. dplyr returns tibbles when it creates a table, and tibble() builds one by hand, column by column. In this book the two behave the same.

tibble(lga = c("Banjul", "Basse"), eas = c(40, 32))
#> # A tibble: 2 × 2
#>   lga      eas
#>   <chr>  <dbl>
#> 1 Banjul    40
#> 2 Basse     32

2.6 The pipe and the verbs of dplyr

Most of the data work of this book uses dplyr, a package of functions, called verbs, that each take a table and return a new one. The pipe |> chains them. x |> f(y) is the same as f(x, y), so a sequence of steps reads from top to bottom, in the order it runs. Read the pipe as “then”.

filter() keeps the rows that meet a condition, and select() keeps columns.

eas |>
  filter(lga == "Basse", households < 25) |>
  select(ea_id, district, households)
#>     ea_id district households
#> 1 8041025  Kantora         19
#> 2 8072020    Sandu         22
#> 3 8031012   Tumana          7
#> 4 8032010   Tumana         20
#> 5 8012040   Jimara         24
#> 6 8012045   Jimara          1

Two equal signs test equality, and a comma between conditions means that both must hold. Inside a dplyr verb, columns are named directly, without eas$. The result shows the EAs of Basse that hold fewer households than a take of 25, which Chapter 11 merges with a neighbor.

mutate() adds or changes columns, computed from the others. arrange() sorts the rows, and desc() reverses the order.

inputs |>
  mutate(eas = eas_urban + eas_rural,
         interviewed = selected * completed) |>
  select(lga, eas, selected, interviewed) |>
  arrange(desc(eas))
#>           lga eas selected interviewed
#> 1     Brikama  50     1250    1188.750
#> 2    Kanifing  46     1150    1026.950
#> 3      Banjul  40     1000     905.000
#> 4     Kerewan  32      800     770.400
#> 5       Basse  32      763     704.249
#> 6 Janjanbureh  28      696     675.120
#> 7  Mansakonko  27      675     652.725
#> 8     Kuntaur  26      651     626.262

summarise() reduces a table to one row of summaries. With .by, it gives one row per group instead. n() counts the rows of each group.

eas |>
  summarise(eas = n(), households = sum(households), .by = lga)
#>           lga  eas households
#> 1      Banjul   93       6600
#> 2       Basse  498      24608
#> 3     Brikama 2271     148137
#> 4 Janjanbureh  324      15646
#> 5    Kanifing  879      65218
#> 6     Kerewan  532      27773
#> 7     Kuntaur  249      11278
#> 8  Mansakonko  208      11853

count() is a short form for the most common summary, the number of rows per group. With two grouping columns it counts every combination.

eas |>
  count(lga, urban_rural)
#>            lga urban_rural    n
#> 1       Banjul       Urban   93
#> 2        Basse       Rural  357
#> 3        Basse       Urban  141
#> 4      Brikama       Rural  717
#> 5      Brikama       Urban 1554
#> 6  Janjanbureh       Rural  272
#> 7  Janjanbureh       Urban   52
#> 8     Kanifing       Urban  879
#> 9      Kerewan       Rural  413
#> 10     Kerewan       Urban  119
#> 11     Kuntaur       Rural  233
#> 12     Kuntaur       Urban   16
#> 13  Mansakonko       Rural  169
#> 14  Mansakonko       Urban   39

mutate() also takes .by, and then computes within each group. Each EA’s share of its LGA’s households needs the LGA total on every row.

eas |>
  mutate(share = households / sum(households), .by = lga) |>
  slice_head(n = 3)
#>     ea_id    lga       district          ward urban_rural
#> 1 1021001 Banjul Banjul Central New Town East       Urban
#> 2 1021002 Banjul Banjul Central New Town East       Urban
#> 3 1021003 Banjul Banjul Central New Town East       Urban
#>   households       share
#> 1         81 0.012272727
#> 2         55 0.008333333
#> 3         91 0.013787879

if_else() chooses between two values, element by element, according to a condition. across() applies one function to several columns at once, such as rounding every numeric column of a table before printing it.

inputs |>
  mutate(reached = if_else(mcpr_rse <= 0.10, "yes", "no")) |>
  select(lga, mcpr, mcpr_rse, reached) |>
  mutate(across(where(is.numeric), \(x) round(x, 2)))
#>           lga mcpr mcpr_rse reached
#> 1      Banjul 0.22     0.09     yes
#> 2    Kanifing 0.16     0.10     yes
#> 3     Brikama 0.20     0.06     yes
#> 4  Mansakonko 0.14     0.14      no
#> 5     Kerewan 0.21     0.09     yes
#> 6     Kuntaur 0.14     0.12      no
#> 7 Janjanbureh 0.18     0.13      no
#> 8       Basse 0.08     0.14      no

Every verb returns a new table and leaves its input unchanged. To keep the result, assign it, as in inputs <- inputs |> mutate(...). A pipe that ends without an assignment only prints.

2.7 Joining and stacking tables

Planning brings tables of different sources together: a frame with a report, or the requirements of several indicators. left_join() adds to each row of a first table the matching columns of a second, matched on a key column. Here each EA receives the mCPR of its LGA from the report.

eas |>
  left_join(select(inputs, lga, mcpr), by = "lga") |>
  slice_head(n = 3)
#>     ea_id    lga       district          ward urban_rural
#> 1 1021001 Banjul Banjul Central New Town East       Urban
#> 2 1021002 Banjul Banjul Central New Town East       Urban
#> 3 1021003 Banjul Banjul Central New Town East       Urban
#>   households  mcpr
#> 1         81 0.217
#> 2         55 0.217
#> 3         91 0.217

A row of the first table without a match keeps NA in the new columns. A join on a misspelled LGA name fails silently that way, so count the missing values after a join.

bind_rows() stacks tables with the same columns, one under the other. The book builds a table of requirements that way in Chapter 8, with one block of rows per indicator.

bind_rows(
  mutate(inputs, lga, indicator = "mcpr", p = mcpr, .keep = "none"),
  mutate(inputs, lga, indicator = "vaccination", p = vacc, .keep = "none")
) |>
  arrange(lga) |>
  slice_head(n = 4)
#>      lga   indicator     p
#> 1 Banjul        mcpr 0.217
#> 2 Banjul vaccination 0.769
#> 3  Basse        mcpr 0.078
#> 4  Basse vaccination 0.849

With .keep = "none", mutate() keeps only the columns it names and drops the others.

2.8 Applying a function to each element

Many functions of R take a vector and work on every element. Some do not, and must be applied to each value in turn. sapply() does that, and returns a vector. Its second argument is the function to apply, often written on the spot as an anonymous function. \(x) x^2 is a function of x that returns its square, and it has no name because it is only used once.

p <- c(0.05, 0.17, 0.50)
sapply(p, \(x) x * (1 - x))
#> [1] 0.0475 0.1411 0.2500

The product \(p(1 - p)\) needs no sapply(), since arithmetic already works element by element. The form matters for functions that take one value at a time, such as the sample size functions of svyplan, which Chapter 8 applies over a range of proportions in exactly this way.

lapply() does the same and returns a list, which is the form to use when each result is a table.

2.9 Lists

A list holds objects of any type and length, each under a name. The results of svyplan and samplyr functions are lists, with the main value and the details that produced it. $ extracts an element by name, as it does a column of a data frame.

banjul <- list(lga = "Banjul", eas = 40, households = c(81, 55, 91))
banjul$households
#> [1] 81 55 91
names(banjul)
#> [1] "lga"        "eas"        "households"

str() shows what a list holds. When a function returns a list whose contents are not obvious, str() and the function’s help page are the place to start. Chapter 8 reads the sample size out of an n_prop() result with $n.

A list of tables, each built by lapply(), becomes one table with bind_rows(). Its .id argument records which element each row came from.

lapply(c("Urban", "Rural"), \(r)
  eas |>
    filter(urban_rural == r) |>
    summarise(eas = n(), median_households = median(households))
) |>
  setNames(c("Urban", "Rural")) |>
  bind_rows(.id = "residence")
#>   residence  eas median_households
#> 1     Urban 2893                71
#> 2     Rural 2161                47

2.10 Writing a function

A computation repeated with different inputs belongs in a function. function() creates one. Its arguments are named in the parentheses, and the value of its last line is returned. The households interviewed in an LGA are its households selected times its completion rate, and the women found divided by that number give the women per interviewed household.

women_per_household <- function(selected, completed, women) {
  interviewed <- selected * completed
  women / interviewed
}
women_per_household(1000, 0.905, 1021)
#> [1] 1.128177

inputs |>
  mutate(women_hh = women_per_household(selected, completed, women)) |>
  select(lga, women_hh)
#>           lga women_hh
#> 1      Banjul 1.128177
#> 2    Kanifing 1.697259
#> 3     Brikama 2.077813
#> 4  Mansakonko 1.623961
#> 5     Kerewan 1.908100
#> 6     Kuntaur 2.187583
#> 7 Janjanbureh 1.943358
#> 8       Basse 2.889603

The function works on single values and on whole columns, since every step inside it does. The files of the R/ folder of this book are functions of this kind, read into a session with source(). source("R/gambia.R"), for example, defines gmb_inputs() and gmb_design(), which later chapters use to rebuild the Gambia inputs and design in one line.

2.11 Random numbers and seeds

A probability sample is drawn with random numbers, and the computer generates them from a seed. The same seed gives the same numbers, so a sample drawn with a recorded seed can be drawn again, exactly, by anyone. set.seed() fixes the seed, and sample() draws without replacement from a vector.

basse <- eas |> filter(lga == "Basse")

set.seed(2025)
sample(basse$ea_id, 3)
#> [1] "8021045" "8012039" "8021068"
set.seed(2025)
sample(basse$ea_id, 3)
#> [1] "8021045" "8012039" "8021068"

The two draws are identical. Without set.seed(), every run gives a different sample. samplyr takes the seed as an argument of execute(), and the sample design report records it (Chapter 14).

2.12 A first plot

ggplot2 builds a plot from a table, in layers. ggplot() names the table and maps its columns to the axes with aes(), and a geom_ function draws the layer. + adds layers and settings. The plot below shows how many households the EAs of each LGA hold.

ggplot(eas, aes(x = households, y = lga)) +
  geom_boxplot() +
  geom_vline(xintercept = 25, linetype = "dashed") +
  labs(x = "Households per EA", y = NULL)

Box plots of the number of households per EA for the eight LGAs. Most EAs hold between about 40 and 80 households in every LGA, with a few below 25 and some above 120.

Households per EA in each LGA of the Gambia frame. The dashed line marks a take of 25 households.

Most EAs hold between 40 and 80 households, and a few in every LGA but Banjul hold fewer than a take of 25. The book’s other plots, of precision across virtual surveys or of clusters on a map, are built in the same way, with more layers.

2.13 When R stops

R stops at the first command it cannot run and prints an error. The message names the function that failed and, in dplyr, svyplan and samplyr, what it expected. A misspelled column is the most common case.

eas |>
  filter(LGA == "Basse")
#> Error in `filter()`:
#> ℹ In argument: `LGA == "Basse"`.
#> Caused by error:
#> ! object 'LGA' not found

R distinguishes upper and lower case, so LGA is not lga. The message says that no object called LGA was found, since the frame has no column of that name, and names(eas) lists the ones it has. Read the whole message before changing the code. A warning is different. R prints it, runs the command to the end and returns a result, which may still be wrong. Execution of a samplyr design warns, for example, when a cluster holds fewer households than its take, and the warning says which.

2.14 From Stata or SPSS

A reader who knows Stata will recognize most of this chapter under other names. keep if is filter(), keep and drop of variables are select(), generate and replace are mutate(), collapse is summarise() with .by, bysort before a command is .by inside it, merge is left_join(), and append is bind_rows(). Two differences matter more than the names. R holds many tables in memory at once, each under its own name, where Stata holds one. And a command of R returns a result without changing its input, so a table changes only when the result is assigned back to its name. SPSS users will find the same correspondence, with SELECT IF for filter() and AGGREGATE for summarise().

2.15 Where to learn more

R for Data Science (Wickham et al. 2023) teaches the dplyr and ggplot2 approach of this chapter in full, and is free online at https://r4ds.hadley.nz. The help pages and vignettes of each package, opened with vignette(package = "samplyr"), document the functions the book uses. When code fails, the message names the function that failed. Read the message before searching the web for it, since the messages of svyplan and samplyr usually say what to change.

2.16 Exercises

  1. Count the EAs of the frame that hold fewer than 25 households, in each LGA.
  2. Add to inputs a column eas, the EAs selected in each LGA in 2019-20, and find the LGA with the most.
  3. Write a function rse(se, estimate) that returns the relative standard error, and apply it to the columns mcpr_se and mcpr of inputs. Compare the result with the column mcpr_rse.
  4. Draw 5 EAs of Kuntaur at random with seed 1. Run the code twice and check that the sample does not change.
  1. eas |> filter(households < 25) |> count(lga). Banjul has none and does not appear in the result, and Brikama has the most, 27.
  2. inputs |> mutate(eas = eas_urban + eas_rural) |> arrange(desc(eas)) puts Brikama first, with 50 EAs.
  3. rse <- function(se, estimate) se / estimate, then inputs |> mutate(rse = rse(mcpr_se, mcpr)) |> select(lga, rse, mcpr_rse). The two columns agree up to the rounding of the published standard errors.
  4. kuntaur <- filter(eas, lga == "Kuntaur"), then set.seed(1) followed by sample(kuntaur$ea_id, 5). The seed must be set again before each draw.