Vectorization and loop functionals

Introduction to vectorization and loop functionals
module 4
week 5
R
programming
functions
Author
Affiliation

Department of Biostatistics, Johns Hopkins

Published

September 27, 2022

Pre-lecture materials

Read ahead

Read ahead

Before class, you can prepare by reading the following materials:

  1. https://rafalab.github.io/dsbook/programming-basics.html#vectorization

Acknowledgements

Material for this lecture was borrowed and adopted from

Learning objectives

Learning objectives

At the end of this lesson you will:

  • Understand how to perform vector arithmetics in R
  • Implement the 5 functional loops in R (vs e.g. for loops) in R

Vectorization

Writing for and while loops are useful and easy to understand, but in R we rarely use them.

As you learn more R, you will realize that vectorization is preferred over for-loops since it results in shorter and clearer code.

Vector arithmetics

Rescaling a vector

In R, arithmetic operations on vectors occur element-wise. For a quick example, suppose we have height in inches:

inches <- c(69, 62, 66, 70, 70, 73, 67, 73, 67, 70)

and want to convert to centimeters.

Notice what happens when we multiply inches by 2.54:

inches * 2.54
 [1] 175.26 157.48 167.64 177.80 177.80 185.42 170.18 185.42 170.18 177.80

In the line above, we multiplied each element by 2.54.

Similarly, if for each entry we want to compute how many inches taller or shorter than 69 inches (the average height for males), we can subtract it from every entry like this:

inches - 69
 [1]  0 -7 -3  1  1  4 -2  4 -2  1

Two vectors

If we have two vectors of the same length, and we sum them in R, they will be added entry by entry as follows:

x <- 1:10
y <- 1:10 
x + y
 [1]  2  4  6  8 10 12 14 16 18 20

The same holds for other mathematical operations, such as -, * and /.

x <- 1:10
sqrt(x)
 [1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427
 [9] 3.000000 3.162278
y <- 1:10
x*y
 [1]   1   4   9  16  25  36  49  64  81 100

Functional loops

While for loops are perfectly valid, when you use vectorization in an element-wise fashion, there is no need for for loops because we can apply what are called functional loops.

Functional loops are functions that help us apply the same function to each entry in a vector, matrix, data frame, or list. Here are a list of them:

  • lapply(): Loop over a list and evaluate a function on each element

  • sapply(): Same as lapply but try to simplify the result

  • apply(): Apply a function over the margins of an array

  • tapply(): Apply a function over subsets of a vector

  • mapply(): Multivariate version of lapply (won’t cover)

An auxiliary function split() is also useful, particularly in conjunction with lapply().

lapply()

The lapply() function does the following simple series of operations:

  1. it loops over a list, iterating over each element in that list
  2. it applies a function to each element of the list (a function that you specify)
  3. and returns a list (the l in lapply() is for “list”).

This function takes three arguments: (1) a list X; (2) a function (or the name of a function) FUN; (3) other arguments via its ... argument. If X is not a list, it will be coerced to a list using as.list().

The body of the lapply() function can be seen here.

lapply
function (X, FUN, ...) 
{
    FUN <- match.fun(FUN)
    if (!is.vector(X) || is.object(X)) 
        X <- as.list(X)
    .Internal(lapply(X, FUN))
}
<bytecode: 0x14f92f928>
<environment: namespace:base>
Note

The actual looping is done internally in C code for efficiency reasons.

It is important to remember that lapply() always returns a list, regardless of the class of the input.

Example

Here’s an example of applying the mean() function to all elements of a list. If the original list has names, the the names will be preserved in the output.

x <- list(a = 1:5, b = rnorm(10))
x
$a
[1] 1 2 3 4 5

$b
 [1] -0.796902151 -0.704764494  2.602279644  0.342396072  0.959892466
 [6]  0.001693647 -0.038861708  0.413760458 -0.740300144 -1.696169815
lapply(x, mean)
$a
[1] 3

$b
[1] 0.0343024

Notice that here we are passing the mean() function as an argument to the lapply() function.

Functions in R can be used this way and can be passed back and forth as arguments just like any other object inR.

When you pass a function to another function, you do not need to include the open and closed parentheses () like you do when you are calling a function.

Example

Here is another example of using lapply().

x <- list(a = 1:4, b = rnorm(10), c = rnorm(20, 1), d = rnorm(100, 5))
lapply(x, mean)
$a
[1] 2.5

$b
[1] -0.1328501

$c
[1] 1.227173

$d
[1] 5.012158

You can use lapply() to evaluate a function multiple times each with a different argument.

Next is an example where I call the runif() function (to generate uniformly distributed random variables) four times, each time generating a different number of random numbers.

x <- 1:4
lapply(x, runif)
[[1]]
[1] 0.3924746

[[2]]
[1] 0.807656 0.852134

[[3]]
[1] 0.9680554 0.6216622 0.4746080

[[4]]
[1] 0.09363509 0.80682941 0.44572025 0.55164581
What happened?

When you pass a function to lapply(), lapply() takes elements of the list and passes them as the first argument of the function you are applying.

In the above example, the first argument of runif() is n, and so the elements of the sequence 1:4 all got passed to the n argument of runif().

Functions that you pass to lapply() may have other arguments. For example, the runif() function has a min and max argument too.

Question

In the example above I used the default values for min and max.

  • How would you be able to specify different values for that in the context of lapply()?

Here is where the ... argument to lapply() comes into play. Any arguments that you place in the ... argument will get passed down to the function being applied to the elements of the list.

Here, the min = 0 and max = 10 arguments are passed down to runif() every time it gets called.

x <- 1:4
lapply(x, runif, min = 0, max = 10)
[[1]]
[1] 7.339994

[[2]]
[1] 6.159324 4.167184

[[3]]
[1] 1.3182169 6.3869630 0.2614679

[[4]]
[1] 7.640224 1.984159 9.285444 2.845784

So now, instead of the random numbers being between 0 and 1 (the default), the are all between 0 and 10.

The lapply() function (and its friends) makes heavy use of anonymous functions. Anonymous functions are like members of Project Mayhem—they have no names. These functions are generated “on the fly” as you are using lapply(). Once the call to lapply() is finished, the function disappears and does not appear in the workspace.

Example

Here I am creating a list that contains two matrices.

x <- list(a = matrix(1:4, 2, 2), b = matrix(1:6, 3, 2)) 
x
$a
     [,1] [,2]
[1,]    1    3
[2,]    2    4

$b
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

Suppose I wanted to extract the first column of each matrix in the list. I could write an anonymous function for extracting the first column of each matrix.

lapply(x, function(elt) { elt[,1] })
$a
[1] 1 2

$b
[1] 1 2 3

Notice that I put the function() definition right in the call to lapply().

This is perfectly legal and acceptable. You can put an arbitrarily complicated function definition inside lapply(), but if it’s going to be more complicated, it’s probably a better idea to define the function separately.

For example, I could have done the following.

f <- function(elt) {
        elt[, 1]
}
lapply(x, f)
$a
[1] 1 2

$b
[1] 1 2 3
Note

Now the function is no longer anonymous; its name is f.

Whether you use an anonymous function or you define a function first depends on your context. If you think the function f is something you are going to need a lot in other parts of your code, you might want to define it separately. But if you are just going to use it for this call to lapply(), then it is probably simpler to use an anonymous function.

sapply()

The sapply() function behaves similarly to lapply(); the only real difference is in the return value. sapply() will try to simplify the result of lapply() if possible. Essentially, sapply() calls lapply() on its input and then applies the following algorithm:

  • If the result is a list where every element is length 1, then a vector is returned

  • If the result is a list where every element is a vector of the same length (> 1), a matrix is returned.

  • If it can’t figure things out, a list is returned

Here’s the result of calling lapply().

x <- list(a = 1:4, b = rnorm(10), c = rnorm(20, 1), d = rnorm(100, 5))
lapply(x, mean)
$a
[1] 2.5

$b
[1] -0.7692304

$c
[1] 1.1845

$d
[1] 5.011145

Notice that lapply() returns a list (as usual), but that each element of the list has length 1.

Here’s the result of calling sapply() on the same list.

sapply(x, mean) 
         a          b          c          d 
 2.5000000 -0.7692304  1.1844997  5.0111453 

Because the result of lapply() was a list where each element had length 1, sapply() collapsed the output into a numeric vector, which is often more useful than a list.

split()

The split() function takes a vector or other objects and splits it into groups determined by a factor or list of factors.

The arguments to split() are

str(split)
function (x, f, drop = FALSE, ...)  

where

  • x is a vector (or list) or data frame
  • f is a factor (or coerced to one) or a list of factors
  • drop indicates whether empty factors levels should be dropped

The combination of split() and a function like lapply() or sapply() is a common paradigm in R. The basic idea is that you can take a data structure, split it into subsets defined by another variable, and apply a function over those subsets. The results of applying that function over the subsets are then collated and returned as an object. This sequence of operations is sometimes referred to as “map-reduce” in other contexts.

Here we simulate some data and split it according to a factor variable. Note that we use the gl() function to “generate levels” in a factor variable.

x <- c(rnorm(10), runif(10), rnorm(10, 1))
f <- gl(3, 10) # generate factor levels
f
 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
Levels: 1 2 3
split(x, f)
$`1`
 [1]  0.06440437  1.78480833 -0.94373825  1.94781191 -0.16936618 -0.58442286
 [7]  1.23801276  0.02465268 -0.35022800 -0.03086819

$`2`
 [1] 0.1623650 0.7931292 0.5370609 0.6692380 0.2197358 0.2657368 0.6490295
 [8] 0.2862331 0.8169028 0.9344586

$`3`
 [1]  0.13424958  0.31285258  2.39555383 -0.11859862 -0.08085121 -0.17574475
 [7] -1.08308465  0.18204113  1.13764707  0.56204495

A common idiom is split followed by an lapply.

lapply(split(x, f), mean)
$`1`
[1] 0.2981067

$`2`
[1] 0.533389

$`3`
[1] 0.326611

Splitting a Data Frame

library(datasets)
head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

We can split the airquality data frame by the Month variable so that we have separate sub-data frames for each month.

s <- split(airquality, airquality$Month)
str(s)
List of 5
 $ 5:'data.frame':  31 obs. of  6 variables:
  ..$ Ozone  : int [1:31] 41 36 12 18 NA 28 23 19 8 NA ...
  ..$ Solar.R: int [1:31] 190 118 149 313 NA NA 299 99 19 194 ...
  ..$ Wind   : num [1:31] 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
  ..$ Temp   : int [1:31] 67 72 74 62 56 66 65 59 61 69 ...
  ..$ Month  : int [1:31] 5 5 5 5 5 5 5 5 5 5 ...
  ..$ Day    : int [1:31] 1 2 3 4 5 6 7 8 9 10 ...
 $ 6:'data.frame':  30 obs. of  6 variables:
  ..$ Ozone  : int [1:30] NA NA NA NA NA NA 29 NA 71 39 ...
  ..$ Solar.R: int [1:30] 286 287 242 186 220 264 127 273 291 323 ...
  ..$ Wind   : num [1:30] 8.6 9.7 16.1 9.2 8.6 14.3 9.7 6.9 13.8 11.5 ...
  ..$ Temp   : int [1:30] 78 74 67 84 85 79 82 87 90 87 ...
  ..$ Month  : int [1:30] 6 6 6 6 6 6 6 6 6 6 ...
  ..$ Day    : int [1:30] 1 2 3 4 5 6 7 8 9 10 ...
 $ 7:'data.frame':  31 obs. of  6 variables:
  ..$ Ozone  : int [1:31] 135 49 32 NA 64 40 77 97 97 85 ...
  ..$ Solar.R: int [1:31] 269 248 236 101 175 314 276 267 272 175 ...
  ..$ Wind   : num [1:31] 4.1 9.2 9.2 10.9 4.6 10.9 5.1 6.3 5.7 7.4 ...
  ..$ Temp   : int [1:31] 84 85 81 84 83 83 88 92 92 89 ...
  ..$ Month  : int [1:31] 7 7 7 7 7 7 7 7 7 7 ...
  ..$ Day    : int [1:31] 1 2 3 4 5 6 7 8 9 10 ...
 $ 8:'data.frame':  31 obs. of  6 variables:
  ..$ Ozone  : int [1:31] 39 9 16 78 35 66 122 89 110 NA ...
  ..$ Solar.R: int [1:31] 83 24 77 NA NA NA 255 229 207 222 ...
  ..$ Wind   : num [1:31] 6.9 13.8 7.4 6.9 7.4 4.6 4 10.3 8 8.6 ...
  ..$ Temp   : int [1:31] 81 81 82 86 85 87 89 90 90 92 ...
  ..$ Month  : int [1:31] 8 8 8 8 8 8 8 8 8 8 ...
  ..$ Day    : int [1:31] 1 2 3 4 5 6 7 8 9 10 ...
 $ 9:'data.frame':  30 obs. of  6 variables:
  ..$ Ozone  : int [1:30] 96 78 73 91 47 32 20 23 21 24 ...
  ..$ Solar.R: int [1:30] 167 197 183 189 95 92 252 220 230 259 ...
  ..$ Wind   : num [1:30] 6.9 5.1 2.8 4.6 7.4 15.5 10.9 10.3 10.9 9.7 ...
  ..$ Temp   : int [1:30] 91 92 93 93 87 84 80 78 75 73 ...
  ..$ Month  : int [1:30] 9 9 9 9 9 9 9 9 9 9 ...
  ..$ Day    : int [1:30] 1 2 3 4 5 6 7 8 9 10 ...

Then we can take the column means for Ozone, Solar.R, and Wind for each sub-data frame.

lapply(s, function(x) {
        colMeans(x[, c("Ozone", "Solar.R", "Wind")])
})
$`5`
   Ozone  Solar.R     Wind 
      NA       NA 11.62258 

$`6`
    Ozone   Solar.R      Wind 
       NA 190.16667  10.26667 

$`7`
     Ozone    Solar.R       Wind 
        NA 216.483871   8.941935 

$`8`
   Ozone  Solar.R     Wind 
      NA       NA 8.793548 

$`9`
   Ozone  Solar.R     Wind 
      NA 167.4333  10.1800 

Using sapply() might be better here for a more readable output.

sapply(s, function(x) {
        colMeans(x[, c("Ozone", "Solar.R", "Wind")])
})
               5         6          7        8        9
Ozone         NA        NA         NA       NA       NA
Solar.R       NA 190.16667 216.483871       NA 167.4333
Wind    11.62258  10.26667   8.941935 8.793548  10.1800

Unfortunately, there are NAs in the data so we cannot simply take the means of those variables. However, we can tell the colMeans function to remove the NAs before computing the mean.

sapply(s, function(x) {
        colMeans(x[, c("Ozone", "Solar.R", "Wind")], 
                 na.rm = TRUE)
})
                5         6          7          8         9
Ozone    23.61538  29.44444  59.115385  59.961538  31.44828
Solar.R 181.29630 190.16667 216.483871 171.857143 167.43333
Wind     11.62258  10.26667   8.941935   8.793548  10.18000

tapply

tapply() is used to apply a function over subsets of a vector. It can be thought of as a combination of split() and sapply() for vectors only. I’ve been told that the “t” in tapply() refers to “table”, but that is unconfirmed.

str(tapply)
function (X, INDEX, FUN = NULL, ..., default = NA, simplify = TRUE)  

The arguments to tapply() are as follows:

  • X is a vector
  • INDEX is a factor or a list of factors (or else they are coerced to factors)
  • FUN is a function to be applied
  • … contains other arguments to be passed FUN
  • simplify, should we simplify the result?
Example

Given a vector of numbers, one simple operation is to take group means.

## Simulate some data
x <- c(rnorm(10), runif(10), rnorm(10, 1))
## Define some groups with a factor variable
f <- gl(3, 10)   
f
 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
Levels: 1 2 3
tapply(x, f, mean)
        1         2         3 
0.2927136 0.2936399 1.0340813 

We can also apply functions that return more than a single value. In this case, tapply() will not simplify the result and will return a list. Here’s an example of finding the range() (min and max) of each sub-group.

tapply(x, f, range)
$`1`
[1] -1.217068  1.723239

$`2`
[1] 0.0620568 0.8443268

$`3`
[1] -0.1079284  2.8115679

apply()

The apply() function is used to a evaluate a function (often an anonymous one) over the margins of an array. It is most often used to apply a function to the rows or columns of a matrix (which is just a 2-dimensional array). However, it can be used with general arrays, for example, to take the average of an array of matrices. Using apply() is not really faster than writing a loop, but it works in one line and is highly compact.

str(apply)
function (X, MARGIN, FUN, ..., simplify = TRUE)  

The arguments to apply() are

  • X is an array
  • MARGIN is an integer vector indicating which margins should be “retained”.
  • FUN is a function to be applied
  • ... is for other arguments to be passed to FUN
Example

Here I create a 20 by 10 matrix of Normal random numbers. I then compute the mean of each column.

x <- matrix(rnorm(200), 20, 10)
head(x)
            [,1]       [,2]        [,3]       [,4]       [,5]       [,6]
[1,] -0.08951039  0.8826521 -0.08872757 -0.1902191  1.6645398 -0.6256195
[2,] -1.61681249 -0.1291864 -0.33969902  0.0642613  0.3666109  0.1417229
[3,] -0.04658801 -0.3518867 -1.19269194  0.5000525  0.7995802 -0.8268586
[4,]  0.54126740 -0.5923315  0.59592538 -1.3801277  0.9194444  0.6511138
[5,]  0.02298819 -1.2806856 -0.36783197 -0.8432676 -1.2392163 -0.4812132
[6,] -0.27934449 -1.0370041  0.74642687 -2.1841962  0.3488571 -0.6985333
            [,7]       [,8]        [,9]       [,10]
[1,]  1.54160420 -0.5170260 -0.52851441 -0.04676887
[2,] -1.46016301 -1.2740124  0.05790032 -1.42846117
[3,] -0.57536442  2.0125221 -1.91502406 -1.36074140
[4,]  0.58692626 -0.6922853  0.06218197 -0.10036921
[5,]  0.03727834  0.1837202  0.26596992 -0.59420697
[6,] -0.02896566  0.5216695 -0.74571287  0.29136921
apply(x, 2, mean)  ## Take the mean of each column
 [1] -0.32908184 -0.19267585  0.04411986 -0.21452934 -0.11431928 -0.21070416
 [7]  0.27329343 -0.21840568 -0.41166243 -0.28090778
Example

I can also compute the sum of each row.

apply(x, 1, sum)   ## Take the mean of each row
 [1]  2.0024103 -5.6178391 -2.9570003  0.5917455 -4.2964651 -3.0654338
 [7] -1.9762763 -4.2211525 -3.3652473 -0.6591509 -1.8506994 -3.4277422
[13] -0.9036821  0.9532504 -0.1092196  2.6233840  2.6924633 -1.8723594
[19] -4.1938965 -3.4445502
Note

In both calls to apply(), the return value was a vector of numbers.

You’ve probably noticed that the second argument is either a 1 or a 2, depending on whether we want row statistics or column statistics. What exactly is the second argument to apply()?

The MARGIN argument essentially indicates to apply() which dimension of the array you want to preserve or retain.

So when taking the mean of each column, I specify

apply(x, 2, mean)

because I want to collapse the first dimension (the rows) by taking the mean and I want to preserve the number of columns. Similarly, when I want the row sums, I run

apply(x, 1, mean)

because I want to collapse the columns (the second dimension) and preserve the number of rows (the first dimension).

Col/Row Sums and Means

Pro-tip

For the special case of column/row sums and column/row means of matrices, we have some useful shortcuts.

  • rowSums = apply(x, 1, sum)
  • rowMeans = apply(x, 1, mean)
  • colSums = apply(x, 2, sum)
  • colMeans = apply(x, 2, mean)

The shortcut functions are heavily optimized and hence are much faster, but you probably won’t notice unless you’re using a large matrix.

Another nice aspect of these functions is that they are a bit more descriptive. It’s arguably more clear to write colMeans(x) in your code than apply(x, 2, mean).

Other Ways to Apply

You can do more than take sums and means with the apply() function.

Example

For example, you can compute quantiles of the rows of a matrix using the quantile() function.

x <- matrix(rnorm(200), 20, 10)
head(x)
            [,1]        [,2]         [,3]        [,4]       [,5]       [,6]
[1,]  0.30116593 -0.22143862 -0.780484437  0.24715546  0.4620109 -0.1284762
[2,] -1.02790308 -0.92858900  0.191527407  0.69079520 -0.2844016  0.3033426
[3,] -0.07119538 -0.06317295 -0.987710196 -0.33902017  0.2571209  0.5702837
[4,]  1.12855517  1.73876299 -2.037467412  0.06666361 -1.6490073 -1.0061759
[5,]  1.00533831 -1.29756896  0.009980026  1.98505348 -0.0113328 -0.2182344
[6,]  0.05762476 -0.28615154 -0.517267972  1.07147513  1.4076715  2.2987914
           [,7]       [,8]       [,9]       [,10]
[1,] -0.0770105 -0.0758423 -0.2742897 -1.06783913
[2,] -0.4108593 -0.7534294 -1.2058456 -0.74607337
[3,] -0.9714008  0.1451234 -1.4040156 -0.03308528
[4,] -1.5909674 -0.7444157 -1.6793615 -0.09789561
[5,]  0.2916761 -2.4666819 -0.9916369  0.99983123
[6,]  0.6401452  1.1482895  1.0475003 -0.69766008
## Get row quantiles
apply(x, 1, quantile, probs = c(0.25, 0.75))    
          [,1]        [,2]       [,3]        [,4]       [,5]       [,6]
25% -0.2610769 -0.88479910 -0.8133057 -1.63449728 -0.7982863 -0.2002075
75%  0.1664060  0.07254515  0.1005712  0.02552381  0.8227924  1.1290859
          [,7]       [,8]     [,9]       [,10]       [,11]      [,12]
25% -0.3483229 -0.2178852 0.142347 -0.00305639 -0.05045378 -0.8347654
75%  0.2779571  0.6790140 1.226393  0.95341826  0.90565824  0.7197274
         [,13]       [,14]      [,15]      [,16]      [,17]      [,18]
25% 0.08092159 -0.08878187 -0.8914984 -0.3260444 -0.4409576 -0.7755624
75% 1.22063634  0.63504774 -0.1218225  0.8874655  1.3131417  1.0484453
         [,19]      [,20]
25% -0.1979752 -0.3811029
75%  0.7158692  0.6466877

Notice that I had to pass the probs = c(0.25, 0.75) argument to quantile() via the ... argument to apply().

Vectorizing a Function

Let’s talk about how we can “vectorize” a function.

What this means is that we can write function that typically only takes single arguments and create a new function that can take vector arguments.

This is often needed when you want to plot functions.

Example

Here’s an example of a function that computes the sum of squares given some data, a mean parameter and a standard deviation. The formula is \(\sum_{i=1}^n(x_i-\mu)^2/\sigma^2\).

sumsq <- function(mu, sigma, x) {
        sum(((x - mu) / sigma)^2)
}

This function takes a mean mu, a standard deviation sigma, and some data in a vector x.

In many statistical applications, we want to minimize the sum of squares to find the optimal mu and sigma. Before we do that, we may want to evaluate or plot the function for many different values of mu or sigma.

x <- rnorm(100)       ## Generate some data
sumsq(mu=1, sigma=1, x)  ## This works (returns one value)
[1] 203.2493

However, passing a vector of mus or sigmas won’t work with this function because it’s not vectorized.

sumsq(1:10, 1:10, x)  ## This is not what we want
[1] 105.2917

There’s even a function in R called Vectorize() that automatically can create a vectorized version of your function.

So we could create a vsumsq() function that is fully vectorized as follows.

vsumsq <- Vectorize(sumsq, c("mu", "sigma"))
vsumsq(1:10, 1:10, x)
 [1] 203.24928 122.09428 108.16721 103.66455 101.75042 100.80246 100.28605
 [8]  99.98663  99.80583  99.69400

Pretty cool, right?

Summary

  • The loop functions in R are very powerful because they allow you to conduct a series of operations on data using a compact form

  • The operation of a loop function involves iterating over an R object (e.g. a list or vector or matrix), applying a function to each element of the object, and the collating the results and returning the collated results.

  • Loop functions make heavy use of anonymous functions, which exist for the life of the loop function but are not stored anywhere

  • The split() function can be used to divide an R object in to subsets determined by another variable which can subsequently be looped over using loop functions.

Post-lecture materials

Final Questions

Here are some post-lecture questions to help you think about the material discussed.

Questions
  1. Write a function compute_s_n() that for any given n computes the sum

\[ S_n = 1^2 + 2^2 + 3^2 + \ldots + n^2 \]

Report the value of the sum when \(n\) = 10.

  1. Define an empty numerical vector s_n of size 25 using s_n <- vector("numeric", 25) and store in the results of \(S_1, S_2, \ldots, S_n\) using a for-loop.

  2. Repeat Q3, but this time use sapply().

  3. Plot s_n versus n. Use points defined by \(n= 1, \ldots, 25\)

Additional Resources