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

R tapply() Function - Grouped Statistics

R tapply() Function - Grouped Statistics

R Language Examples R Language Examples

The R tapply() function is used to apply a function to data by group, performing grouped summaries.

tapply() is one of the most commonly used functions for grouped statistics, similar to SQL's GROUP BY.

The syntax of the tapply() function is as follows:

tapply(X, INDEX, FUN, ...)

Parameter Description:

Example

Student score data

scores

<-

c

(

88

,

92

,

76

,

85

,

90

,

95

,

70

,

82

,

89

,

78

)

grade

<-

c

(

"A"

,

"A"

,

"B"

,

"B"

,

"A"

,

"A"

,

"C"

,

"B"

,

"A"

,

"C"

)

Calculate the average score by class

avg_by_grade

<-

tapply

(

scores, grade,

mean

)

print

(

"Average score by class:"

)

print

(

avg_by_grade

)

Calculate multiple statistics by class

result

<-

tapply

(

scores, grade,

function

(

x

)

{

 

c

(

Count

=

length

(

x

)

, mean

=

mean

(

x

)

, maximum

=

max

(

x

)

)

}

)

print

(

"Detailed statistics by class:"

)

print

(

result

)

The output of the code above is:

[1] "各班平均分:"

   A    B    C

90.8 81.0 74.0

[1] "各班详细统计:"

$A

人数 均值 最高

 5.0 90.8 95.0



$B

人数 均值 最高

 3.0 81.0 85.0



$C

人数 均值 最高

 2.0 74.0 78.0

R Language Examples R Language Examples