In the Help documentation for the R language, the function of the Apply function is:
Retruns a vector or array or list of values obtained by applying a function to margins of an array or matrix.
That is, apply sets a function to the array or matrix margins (which can be understood in each row or column of an array), and the vector, array, and list are returned as values.
Simply put, the Apply function is often used to calculate the mean, and value functions of rows or columns in a matrix, as follows:
Define a matrix of 3x2:
Rname = C ("one","One","One", "three" ) = C ("First","second"<- Matrix (1:6, nrow=3, dimnames = List (rname, CNAME))
B is:
First Secondone 1 4two 2 5three 3 6
Continue to cite a few examples:
Apply (b,1, sum)
The above instruction represents a row calculation of matrix B and sums each row separately. The function involves three parameters:
The first parameter refers to the matrix to participate in the calculation;
The second parameter refers to the calculation by row or column, and the 2--is calculated by row, and the column is computed by columns;
The third parameter refers to a specific operation parameter.
The return result of the above instruction is:
One three 5 7
It is worth noting that the Apply function can be calculated for the array you, that is, the array is not necessarily 2-dimensional!!
To give a 3-dimensional case:
First, top a three-dimensional array:
X=array (1:, C (2,3,4))
The three-dimensional array is:
,, 1 [, 1] [, 2] [, 3][1,] 1 3 5[2,] 2 4 6 ,, 2 [, 1] [, 2] [, 3][1,] 7 9 11[2 ,] 8 ,, 3 [, 1] [, 2] [, 3][1,] 17[2,] 18,, 4 [, 1] [, 2] [, 3][1,] 23[2,] 24
Use the following directives:
Apply (x,1, sum)
All odd numbers from 1 to 23 are summed and the result is:
[1] 144 156
Similarly, when the second parameter is changed to 2,
Apply (x,2, sum)
The result is:
[1] 84 100 116
is the sum computed by the second dimension.
When the second parameter is changed to 3,
Apply (x,3,sum)
The result is:
[1] 93 129
That is, the third dimension is calculated as a summation.
For the third parameter of the Apply () function, what function is used for the calculation, the previous example uses sum, and the user-defined function can also be used here. Also use the preceding matrix B for example.
A function that defines the sum of squares is defined:
Myfun <- Function (x) { sum (x^2)}
If you choose to calculate the sum of squares by row, you can use the following directives:
Apply (b,1, Myfun)
The result of the calculation is:
One three 29
In general, when you use apply, you need to use the return value of apply as input in other code, which is especially important here is the dimension of the return value of apply. The above example, even if the sum of each row or column, after using apply, returns a vector, and does not automatically return a column (row) vector because the sum of the Apply computed row (column).
R language Apply () function usage