-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-8_functions_apply.qmd
104 lines (62 loc) · 5.2 KB
/
3-8_functions_apply.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Using apply functions {.unnumbered}
Once you have written a function, you would like to apply it to some piece of data. As described in the previous chapter you can simply enter some values as arguments of the function and run it. However, usually you would like to run the function on all of your data. To do that you could write a for loop that loops through you data and applies the function to the whole dataset. However, there is a special family of functions in R that make it easier to apply your function to a range of different data classes in different ways. This family of functions are called apply functions.
The apply functions make it easier to run functions over vectors, matrixes, and data.frames. We will discuss four functions of the apply family that are regularly used `apply()`, `lapply()`, `sapply()` and `tapply()`.
### Using apply on matrices
The apply function works by "applying" a specified function to an data object. It requires 3 arguments: the data, a so-called "MARGIN", and a function. The data can be a vector, data.frame or a matrix. The MARGIN indicates whether you want to apply the function to the rows or the columns of your data, or both. To apply the function to the rows the MARGIN should be 1, to apply it to the columns it should be 2 and to apply it to both it should be `c(1,2)`. The function can be an existing function, such as `sum()` or `mean()`, or your own custom function.
As an example we will apply the function `max()` to some data, in this case a matrix.
First we create a matrix of 10 by 10.
```{r}
mat <- matrix(1:100,nrow=10)
mat
```
Then we apply our function "max" to the matrix rows, indicated with a 1 (notice that we do not run the function by writing max(), but we just give the name of the function that should be run: max).
```{r}
apply(mat, 1, max)
```
The result of applying the function max to the rows of the matrix is a vector containing the maximal values for each row.
We can also determine the maximal value in each column by using 2 as the MARGIN value.
```{r}
apply(mat, 2, max)
```
As mentionned before, it is also possible to apply the functions to each element in the matrix by using c(1,2). In that case it doesn't make sense to determine the maximum value, so lets take the square root.
```{r}
apply(mat, c(1,2), sqrt)
```
Because sqrt also works on matrices, it is actually unnecessary to use apply to run it for each element in the matrix. In cases where functions cannot directly be run on a matrix, apply offers a short and readible alternative to writing a nested for loop.
### Using lapply on lists to return lists
The lapply function is used to run a function on list objects. Let's assume we have a list of different sized matrices and we would like to know the dimensions of these matrices. We can then run the function "dim" on the list using lapply. lapply only requires a list object and a function as arguments and always returns a list of results.
```{r}
mylist <- list(matrix(1:16,nrow=4), matrix(1:9,nrow=3),matrix(1:4,nrow=2))
lapply(mylist, dim)
```
Because dataframes are lists of lists, it is also possible to run lapply on dataframes. In that case lapply will apply the function to the columns of the data.frame object and it returns a list of values.
```{r}
df <- data.frame("col1"=c(1,1,1,1), "col2"=c(2,2,2,2), "col3"=c(3,3,3,3))
lapply(df, sum)
```
### Using lapply alternative sapply
sapply is a user-friendly version of lapply. The difference with lapply is that sapply tries to turn the list of results into a more user-friendly format, such as a vector or a matrix.
For the first example the results are turned into a matrix.
```{r}
sapply(mylist, dim)
```
For the second example, the results are turned into a vector.
```{r}
sapply(df, sum)
```
There is no difference between lapply and sapply in how the data is used, but it gives you more flexibility in how the results are created.
### Using tapply on groups of data
tapply lets you apply a function on groupings of your data. Imagine that you have a dataset in which a grouping factor separates your data into two groups of patients. With tapply you can apply a function to those two groups separately. The only thing tapply requires is the column you would like to apply the function to, the grouping factor and the function you would like to apply.
```{r}
patients <- data.frame("group"=paste('grp',c(1,1,1,1,1,1,2,2,2,2,2,2),sep='-'), "outcome"=rnorm(12))
patients
tapply(patients$outcome, patients$group, mean)
```
It is also possible to use multiple factors in a list to create groups, which returns a matrix.
```{r}
patients <- data.frame("group"=paste('grp',c(1,1,1,1,1,1,2,2,2,2,2,2),sep='-'),
"serotype"=c("A","B","A","B","A","B","A","B","A","B","A","B"),
"outcome"=rnorm(12))
tapply(patients$outcome, list(patients$group, patients$serotype), mean)
```
These are some (trivial) examples of how you can use the apply family of functions to quickly apply a function to your data. It is possible to do the same thing by using for loops, but apply functions are generally faster to write and read. In some cases using apply to run your function can also increase the speed of your code. More on increasing the speed of your code will follow in later lectures.