R tapply() Function - Grouped Statistics

R 语言实例R Language Example

The R tapply() function is used to apply a function to data by group for grouped summarization.

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

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

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

Parameter description:

  • XThe data vector to be summarized.

  • INDEXGrouping variable (factor or list).

  • FUNThe summary function to apply.

Example

# Student grade 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 average score by class
avg_by_grade <- tapply(scores, grade, mean)
print("Average score per class:")
print(avg_by_grade)

# Calculate multiple statistics by class
result <- tapply(scores, grade, function(x) {
  c(Count= length(x), Mean= mean(x), Max= max(x))
})
print("Detailed statistics by class:")
print(result)

Executing the above code produces the following output:

[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 语言实例R Language Example

Other Extensions