Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R apply() Function - Array Application

R apply() Function - Array Application

R Language Examples R Language Examples

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:

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"

)

print

(

"Score Matrix:"

)

print

(

scores

)

Compute each student's average score by row

row_means

<-

apply

(

scores,

1

,

mean

)

print

(

"Average Score per Student:"

)

print

(

round

(

row_means,

1

)

)

Compute the highest score for each subject by column

col_max

<-

apply

(

scores,

2

,

max

)

print

(

"Highest Score per Subject:"

)

print

(

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 R Language Examples