R apply() Function - Array Application
The R apply() function is used to apply a function to the rows or columns of a matrix or array.
apply() avoids writing explicit loops, making code more concise and efficient.
The syntax of the apply() function is as follows:
apply(X, MARGIN, FUN, ...)
Parameter Description:
-
X Input matrix or array.
-
MARGIN Dimension: 1 means by row, 2 means by column, c(1,2) means both rows and columns.
-
FUN The function to apply.
-
... Extra arguments passed to FUN.
Example
Create a score matrix
scores
<-
matrix
(
c
(
88
,
92
,
76
,
85
,
90
,
90
,
88
,
82
,
78
,
95
,
85
,
91
,
78
,
88
,
92
)
,
nrow
=
5
,
ncol
=
3
)
colnames
(
scores
)
<-
c
(
"Math"
,
"English"
,
"Programming"
)
rownames
(
scores
)
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
)
(
"Score Matrix:"
)
(
scores
)
Compute each student's average score by row
row_means
<-
apply
(
scores,
1
,
mean
)
(
"Average Score per Student:"
)
(
round
(
row_means,
1
)
)
Compute the highest score for each subject by column
col_max
<-
apply
(
scores,
2
,
max
)
(
"Highest Score per Subject:"
)
(
col_max
)
The output of the code above is:
[1] "成绩矩阵:"
数学 英语 编程
张三 88 90 85
李四 92 88 91
王五 76 82 78
赵六 85 78 88
钱七 90 95 92
[1] "每人平均分:"
张三 李四 王五 赵六 钱七
87.7 90.3 78.7 83.7 92.3
[1] "每科最高分:"
数学 英语 编程
92 95 92
R Language Examples