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() can avoid writing explicit loops, making code more concise and efficient.
The syntax of the apply() function is as follows:
apply(X, MARGIN, FUN, ...)
Parameter description:
XInput matrix or array.
MARGINDimension: 1 means by row, 2 means by column, c(1,2) means both rows and columns.
FUNThe function to be applied.
...Additional 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")
print("Score matrix:")
print(scores)
# Calculate the average score for each student by row
row_means <- apply(scores, 1, mean)
print("Average score per person:")
print(round(row_means, 1))
# Calculate the highest score for each subject by column
col_max <- apply(scores, 2, max)
print("Highest score per subject:")
print(col_max)
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)
# Calculate the average score for each student by row
row_means <- apply(scores, 1, mean)
print("Average score per person:")
print(round(row_means, 1))
# Calculate the highest score for each subject by column
col_max <- apply(scores, 2, max)
print("Highest score per subject:")
print(col_max)
Executing the above code produces the following output:
[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
Other extensions
R Language Example