![]() |
VOOZH | about |
In this article, we will explore a method to apply the function to each matrix column by using R Programming Language.
The function 'apply()' is used to apply the function to each column of the matrix. By using these methods provided by R, it is easy to apply the function. The method to apply the function to each column of the matrix is
This method is used to apply the function to each column of the matrix. The syntax is as follows
apply(X, MARGIN, FUN)Where:
In the below example, we calculated mean of each column by using the function apply().
Output:
[1] "original matrix"
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 12 19 25 31 37 43
[2,] 15 21 27 33 39 45
[3,] 17 23 29 35 41 47
[1] "Applying function to each column for calculating mean"
[1] 14.66667 21.00000 27.00000 33.00000 39.00000 45.00000
In the below example, we calculated sum of each column by using the function apply().
Output:
[1] "original matrix"
[,1] [,2] [,3] [,4]
[1,] 55 60 65 70
[2,] 56 61 66 71
[3,] 57 62 67 72
[4,] 58 63 68 73
[5,] 59 64 69 74
[1] "Applying function to each column for calculating sum"
[1] 285 310 335 360
In the below example, we calculated standard deviation of each column by using the function apply().
Output:
[1] "original matrix"
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[1] "Applying function to each column for calculating standard deviation"
[1] 1.581139 1.581139 1.581139 1.581139 1.581139
In the below example, we multiplied each column of elements with an integer 5 by using the function apply().
Output:
[1] "original matrix"
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[1] "Applying function to each column for multiplying"
[,1] [,2] [,3] [,4] [,5]
[1,] 5 30 55 80 105
[2,] 10 35 60 85 110
[3,] 15 40 65 90 115
[4,] 20 45 70 95 120
[5,] 25 50 75 100 125
In Conclusion, we learned about how to apply function to each column of matrix by using the function apply(). R language provides versatile tools and functions while dealing with matrices.