# Applied Functions

The `apply()`

function (and related variants `lapply()`

, `sapply()`

, and `vapply()`

) are designed to perform a given task across a series or subset of elements from a larger whole. The two common arguments for any of these functions are `X =`

and `FUN =`

for indicating the object to act upon and the actual action to take, respectively. Below, we illustrate these basic arguments when using either `apply()`

or `lapply()`

.

## apply()

```
# define an example matrix
M <- matrix(c(0, 5, 2, 5, 1, 9, 8, 0), nrow=2)
M
## [,1] [,2] [,3] [,4]
## [1,] 0 2 1 8
## [2,] 5 5 9 0
```

```
# Take the mean of each row
apply(X = M, MARGIN = 1, FUN = mean)
## [1] 2.75 4.75
```

```
# Same, except for columns and using argument order instead of specifying explicitly
apply(M, 2, mean)
## [1] 2.5 3.5 5.0 4.0
```

```
# Defining custom function since 'mean(x) + 1' is not a part of base R
apply(M, 2, function(x) mean(x) + 1)
## [1] 3.5 4.5 6.0 5.0
```

```
# Extracting values > 3 by row
apply(M, 1, function(x) x[x>3])
## [[1]]
## [1] 8
## [[2]]
## [1] 5 5 9
```

Notice that the last the line of code resulted in a **list** object. This is because the result from `apply()` for each row of the matrix M is comprised of a different number of elements.

## lapply()

Now, we'll look at `lapply()`

which is referred to as 'L'-apply since it's an apply function for list objects; however, `lapply()`

not only returns a list object automatically but also allows the user to apply a function to a list object.

The object and function arguments in `lapply()`

serve the same purpose as in `apply()`

; however, notice that `lapply()`

doesn't require a `MARGIN =`

argument. This is because lists are operated on element by element. In other words, think of lists as having only a single dimension and therefore do not require a dimension be specified.

```
# Define an example list of elements
x1 <- c(1, 9, 7, 9)
x2 <- c(8, 0, 5)
exampleList <- list(x1, x2)
exampleList
## [[1]]
## [1] 1 9 7 9
## [[2]]
## [1] 8 0 5
```

```
lapply(exampleList, mean)
## [[1]]
## [1] 6.5
##
## [[2]]
## [1] 4.333333
```

For information concerning additional arguments that can be used with the apply family of functions, including `sapply()`

and `vapply()`

, please refer to the R Help documentation.