# Day5 Learning Notes : Loop Functions

Writing for and while loops is useful when programming but not particularly easy when working interactively on the command line. Multi-line expressions with curly braces are just not that easy to sort through when working on the command line. R has some functions which implement looping in a compact form to make your life easier.

• 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

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 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.

Note that the actual looping is done internally in C code for efficiency reasons.

It’s important to remember that lapply() always returns a list, regardless of the class of the input. Here’s an example of applying the mean() function to all elements of a list. If the original list has names, the names will be preserved in the output.

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. 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.

Here is another example of using lapply().

You can use lapply() to evaluate a function multiple times each with a different argument. Below, 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.

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. 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.

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

The lapply() function and its friends make heavy use of anonymous functions. Anonymous

functions are like members of Project Mayhem—they have no names. These are 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.

Here I am creating a list that contains two matrices.

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.

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.

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’re going to need a lot in other parts of your code, you might want to define it separately. But if you’re just going to use it for this call to lapply(), then it’s 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().

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.

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

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 the 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.

A common idiom is split followed by an lapply.

## Splitting a Data Frame

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

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

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

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.

Occasionally, we may want to split an R object according to levels defined in more than one variable. We can do this by creating an interaction of the variables with the interaction() function.

With multiple factors and many levels, creating an interaction can result in many levels that are empty.

Notice that there are 4 categories with no data. But we can drop empty levels when we call the split() function.

## 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.

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?

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

We can also take the group means without simplifying the result, which will give us a list. For functions that return a single value, usually, this is not what we want, but it can be done.

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 of each sub-group.

## 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.

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

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

I can also compute the sum of each row.

Note that 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

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

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

## Col/Row Sums and Means

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. For example, you can compute quantiles of the rows of a matrix using the quantile() function.

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

For a higher dimensional example, I can create an array of 2 x 2 matrices and the compute the average of the matrices in the array.

In the call to apply() here, I indicated via the MARGIN argument that I wanted to preserve the first and second dimensions and to collapse the third dimension by taking the mean.

There is a faster way to do this specific operation via the colMeans() function.

In this situation, I might argue that the use of rowMeans() is less readable, but it is substantially faster with large arrays.

## mapply()

The mapply() function is a multivariate apply of sorts which applies a function in parallel over a set of arguments. Recall that lapply() and friends only iterate over a single R object. What if you want to iterate over multiple R objects in parallel? This is what mapply() is for.

The arguments to mapply() are

• FUN is a function to apply
• … contains R objects to apply over
• MoreArgs is a list of other arguments to FUN.
• SIMPLIFY indicates whether the result should be simplified

The mapply() function has a different argument order from lapply() because the function to apply comes first rather than the object to iterate over. The R objects over which we apply the function are given in the … argument because we can apply over an arbitrary number of R objects.

For example, the following is tedious to type

With mapply(), instead we can do

This passes the sequence 1:4 to the first argument of rep() and the sequence 4:1 to the second argument.

Here’s another example for simulating Random Normal variables.

Here we can use mapply() to pass the sequence 1:5 separately to the noise() function so that we

can get 5 sets of random numbers, each with a different length and mean.

The above call to mapply() is the same as

## Vectorizing a Function

The mapply() function can be used to automatically “vectorize” a function. What this means is that it can be used to take a 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.

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

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. However, passing a vector of mus or sigmas won’t work with this function because it’s not vectorized.

Note that the call to sumsq() only produced one value instead of 10 values.

However, we can do what we want to do by using mapply().

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.

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(on the command line)
• 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.

Copied from R Programming for Data Science – Roger D. Peng