Learning R: Iterating Over Data

2026-11-11 22:40:58

Roadmap 📍

  • iteration the process of repeating a set of instructions until a specific condition is met
  • iterate sequentially or in vectorized fashion
  • topics:
    • vectorization: what it is and why it’s fast
    • thinking in vectors: element-wise operations, recycling, logical vectors
    • loops in disguise: the apply() family and purrr::map()
    • for-loops done right: preallocating your output

Vectorization

# look inside the sum() and sqrt() functions
sum
## function (..., na.rm = FALSE)  .Primitive("sum")
sqrt
## function (x)  .Primitive("sqrt")
# look inside the colSums() function that does some tests in R first before passing along
colSums
## function (x, na.rm = FALSE, dims = 1L) 
## {
##     if (is.data.frame(x)) 
##         x <- as.matrix(x)
##     if (!is.array(x) || length(dn <- dim(x)) < 2L) 
##         stop("'x' must be an array of at least two dimensions")
##     if (length(dims) != 1L || dims < 1L || dims > length(dn) - 
##         1L) 
##         stop("invalid 'dims'")
##     n <- prod(dn[id <- seq_len(dims)])
##     dn <- dn[-id]
##     z <- .Internal(colSums(x, n, prod(dn), na.rm))
##     if (length(dn) > 1L) {
##         dim(z) <- dn
##         dimnames(z) <- dimnames(x)[-id]
##     }
##     else names(z) <- dimnames(x)[[dims + 1L]]
##     z
## }
## <bytecode: 0x000001faa2e75210>
## <environment: namespace:base>

Why work with vectors 🤔

x <- runif(1e6)

loop_sqrt <- function(x) {
  out <- numeric(length(x))
  for (i in seq_along(x)) out[i] <- sqrt(x[i] + 2)
  out
}

bench::mark(
  loop       = loop_sqrt(x),
  vectorized = sqrt(x + 2)
)[, c("expression", "median")]
## # A tibble: 2 × 2
##   expression   median
##   <bch:expr> <bch:tm>
## 1 loop        64.23ms
## 2 vectorized   8.38ms
timings <- bench::mark(
  loop           = loop_sqrt(x),
  vectorized     = sqrt(x + 2),
  iterations     = 5,
  check          = FALSE 
) %>% 
mutate(expression = c("Base R", "data.table")) %>%
  dplyr::select(c(expression, min, median))

Working with vectors

some_numbers <- c(1:10)
sqrt(some_numbers + 2)
##  [1] 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427
##  [7] 3.000000 3.162278 3.316625 3.464102

Vectorize your code

data_gapminder_num <- select(gap_dat, is.numeric) # grab any column where is.numeric() is true
colSums(data_gapminder_num) 
##         year      lifeExp          pop    gdpPercap 
## 3.373068e+06 1.013444e+05 5.044047e+10 1.229492e+07
colMeans(data_gapminder_num)
##         year      lifeExp          pop    gdpPercap 
## 1.979500e+03 5.947444e+01 2.960121e+07 7.215327e+03

Functions That Loop For You

apply()

apply(data_gapminder_num, 2, sum)
##         year      lifeExp          pop    gdpPercap 
## 3.373068e+06 1.013444e+05 5.044047e+10 1.229492e+07
head(apply(data_gapminder_num[data_gapminder_num$year == 1952, ], 2, sort))
##      year lifeExp    pop gdpPercap
## [1,] 1952  28.801  60011  298.8462
## [2,] 1952  30.000  63149  299.8503
## [3,] 1952  30.015 120447  328.9406
## [4,] 1952  30.331 147962  331.0000
## [5,] 1952  31.286 153936  339.2965
## [6,] 1952  31.975 160000  362.1463
apply(data_gapminder_num, 2, max)
##         year      lifeExp          pop    gdpPercap 
## 2.007000e+03 8.260300e+01 1.318683e+09 1.135231e+05

lapply() and sapply()

  • lapply() always returns a list

  • sapply() simplifies the output, returning a vector or matrix

Working with lapply() and sapply()

lapply(data_gapminder_num, sum)
## $year
## [1] 3373068
## 
## $lifeExp
## [1] 101344.4
## 
## $pop
## [1] 50440465801
## 
## $gdpPercap
## [1] 12294917
sapply(data_gapminder_num, sum)
##         year      lifeExp          pop    gdpPercap 
## 3.373068e+06 1.013444e+05 5.044047e+10 1.229492e+07

unlist()

unlist(lapply(data_gapminder_num, sum))
##         year      lifeExp          pop    gdpPercap 
## 3.373068e+06 1.013444e+05 5.044047e+10 1.229492e+07

mapply()

  • mapply() applies function across more than one object

Using mapply()

# three vectors
a <- c(1:10)
b <- c(11:20)
c <- c(21:30)

# sum each element together in order (first value of each object, second value, etc)
mapply(sum, a, b, c)
##  [1] 33 36 39 42 45 48 51 54 57 60

mapply() is just apply()

d <- cbind(a, b, c)
d
##        a  b  c
##  [1,]  1 11 21
##  [2,]  2 12 22
##  [3,]  3 13 23
##  [4,]  4 14 24
##  [5,]  5 15 25
##  [6,]  6 16 26
##  [7,]  7 17 27
##  [8,]  8 18 28
##  [9,]  9 19 29
## [10,] 10 20 30
apply(d, 1, sum)
##  [1] 33 36 39 42 45 48 51 54 57 60

Iterating with Tidyverse

# install purr if not already installed
# install.packages("purrr")
map(data_gapminder_num, sum)
## $year
## [1] 3373068
## 
## $lifeExp
## [1] 101344.4
## 
## $pop
## [1] 50440465801
## 
## $gdpPercap
## [1] 12294917
map2(a, b, sum)
## [[1]]
## [1] 12
## 
## [[2]]
## [1] 14
## 
## [[3]]
## [1] 16
## 
## [[4]]
## [1] 18
## 
## [[5]]
## [1] 20
## 
## [[6]]
## [1] 22
## 
## [[7]]
## [1] 24
## 
## [[8]]
## [1] 26
## 
## [[9]]
## [1] 28
## 
## [[10]]
## [1] 30

Note

For-loops

for (int in c(1:10)) { # for each int in the range 1 through 10
  print(int) # print that int
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10

Sampling

# sample our data to keep things small
data_gapminder_sample <- data_gapminder_num[sample(nrow(data_gapminder_num), 20), ]

data_gapminder_sample
##      year lifeExp        pop  gdpPercap
## 126  1977  49.190    3168267  1029.1613
## 1301 1972  56.480      76595  1532.9853
## 798  1977  75.380  113872473 16610.3770
## 993  1992  71.455   88111030  9472.3843
## 1142 1957  73.440    3491938 11653.9730
## 1357 1952  60.396    1127000  2315.1382
## 1226 1957  65.770   28235346  4734.2530
## 50   1957  64.399   19610538  6856.8562
## 1376 1987  71.080    5199318 12037.2676
## 1517 1972  47.620   14706593   915.9851
## 250  1997  78.610   30305843 28954.9259
## 1255 1982  73.750    3279001 10330.9891
## 1039 1982  42.795   12587223   462.2114
## 548  1987  60.190     880397 11864.4084
## 613  1952  33.609    2664249   510.1965
## 989  1972  62.361   55984294  6809.4067
## 1104 2007  80.204    4115771 25185.0091
## 316  1967  46.472     217378  1876.0296
## 299  2002  72.028 1280400000  3119.2809
## 963  1962  44.248    1146757  1055.8960
#example of what we want to print, the log base 10 of the first value in the column gdpPercap
print(log10(data_gapminder_sample$gdpPercap[1]))
## [1] 3.012483
# for demonstration purposes
# for each indexed position in our sampled data
# print the index position and
# the log base 10 of the per capita gdp for that index point
for (index in seq_along(data_gapminder_sample$gdpPercap)) {
  print(index)
  print(log10(data_gapminder_sample$gdpPercap[index]))
}
## [1] 1
## [1] 3.012483
## [1] 2
## [1] 3.185538
## [1] 3
## [1] 4.220379
## [1] 4
## [1] 3.976459
## [1] 5
## [1] 4.066474
## [1] 6
## [1] 3.364577
## [1] 7
## [1] 3.675251
## [1] 8
## [1] 3.836125
## [1] 9
## [1] 4.080528
## [1] 10
## [1] 2.961888
## [1] 11
## [1] 4.461722
## [1] 12
## [1] 4.014142
## [1] 13
## [1] 2.664841
## [1] 14
## [1] 4.074246
## [1] 15
## [1] 2.707737
## [1] 16
## [1] 3.833109
## [1] 17
## [1] 4.401142
## [1] 18
## [1] 3.27324
## [1] 19
## [1] 3.494054
## [1] 20
## [1] 3.023621

Anatomy of a ‘For-loop’

out <- numeric(length(x))   # output: somewhere to store results

for (i in seq_along(x)) {   # for (loop variable in sequence)
  out[i] <- sqrt(x[i])      # body: runs once per iteration
} 

Writing a for-loop

for (index in seq_along(data_gapminder_sample$gdpPercap)) {
  index_number <- index
  log <- log10(data_gapminder_sample$gdpPercap[index])
  cat(paste0("The log base 10 of the index point ", index, " is: ", log, "\n"))
}
## The log base 10 of the index point 1 is: 3.0124834262036
## The log base 10 of the index point 2 is: 3.18553797733498
## The log base 10 of the index point 3 is: 4.22037948985684
## The log base 10 of the index point 4 is: 3.97645930908032
## The log base 10 of the index point 5 is: 4.06647400906966
## The log base 10 of the index point 6 is: 3.3645769259938
## The log base 10 of the index point 7 is: 3.67525146479271
## The log base 10 of the index point 8 is: 3.83612504242298
## The log base 10 of the index point 9 is: 4.08052791469559
## The log base 10 of the index point 10 is: 2.96188838986882
## The log base 10 of the index point 11 is: 4.46172245769608
## The log base 10 of the index point 12 is: 4.01414190543257
## The log base 10 of the index point 13 is: 2.66484066673129
## The log base 10 of the index point 14 is: 4.07424608914852
## The log base 10 of the index point 15 is: 2.7077374684251
## The log base 10 of the index point 16 is: 3.83310927307515
## The log base 10 of the index point 17 is: 4.40114211228811
## The log base 10 of the index point 18 is: 3.27323969635094
## The log base 10 of the index point 19 is: 3.49405448539833
## The log base 10 of the index point 20 is: 3.02362115947219

Storing output with for-loops

# create an empty vector of a known length and data type
gdp_percapita_log <- vector(mode = "double",
                            length = nrow(data_gapminder_sample))

# update the values of the vector as we iterate over gdpPercap
for (i in seq_along(data_gapminder_sample$gdpPercap)){
  gdp_percapita_log[i] <- log10(data_gapminder_sample$gdpPercap[i])
}

# print the vector
gdp_percapita_log
##  [1] 3.012483 3.185538 4.220379 3.976459 4.066474 3.364577
##  [7] 3.675251 3.836125 4.080528 2.961888 4.461722 4.014142
## [13] 2.664841 4.074246 2.707737 3.833109 4.401142 3.273240
## [19] 3.494054 3.023621

Takeaway

  • R is built on vectors, so let functions work on a whole vector at once
  • Vectorized functions are fast
  • Think in element-wise operations (e.g., sum(x > 70), mean(x > 70))
  • The apply() family and purrr::map() are loops
    • lapply() / map() return a list; sapply() simplifies
    • mapply() / map2() iterate over more than one object
  • Write a for loop when each step depends on the last
    • preallocate your output first