R tapply() Function - Grouped Statistics
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:
-
X The data vector to summarize.
-
INDEX The grouping variable (a factor or list).
-
FUN The summary function to apply.
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
)
(
"Average score by class:"
)
(
avg_by_grade
)
Calculate multiple statistics by class
result
<-
tapply
(
scores, grade,
function
(
x
)
{
c
(
Count
=
length
(
x
)
, mean
=
mean
(
x
)
, maximum
=
max
(
x
)
)
}
)
(
"Detailed statistics by class:"
)
(
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