## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# How to do it...

To apply a function to all elements of a collection with lapply and sapply, follow these instructions:

1. Operate on a simple vector:
```> lapply(c(1,2,3), sqrt)

[]
 1

[]
 1.414214

[]
 1.732051 ```
1. Use lapply and sapply to calculate the means of a list of collections:
```> x <- list(a = 1:10, b = c(1,10,100,1000),     c=seq(5,50,by=5))
> lapply(x, mean)

\$a
 5.5
\$b
 277.75
\$c
 27.5

> class(lapply(x,mean))
 "list"

> sapply(x, mean)

a      b      c
5.50 277.75  27.50

> class(sapply(x,mean))

 "numeric"```
1. Calculate the minimum value for each variable in the auto data frame:
```> sapply(auto[,2:8], min)
mpg    cylinders displacement   horsepower
9            3           68           46
weight acceleration   model_year
1613            8           70 ```

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required