YouTip LogoYouTip

R Func Apply

# R apply() Function - Array Application [![Image 3: 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() can avoid writing explicit loops, making the code more concise and efficient. The syntax format of the apply() function is as follows: apply(X, MARGIN, FUN, ...) **Parameter Description:** * **X** Input matrix or array. * **MARGIN** Dimension: 1 means by row, 2 means by column, c(1,2) means both rows and columns. * **FUN** The function to apply. * **...** Additional arguments passed to FUN. ## Example ```r # Create 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 Each Student's Average Score by Row row_means <-apply(scores, 1, mean) print("Average Score per Student:") print(round(row_means, 1)) # Calculate the Maximum Score for Each Subject by Column col_max <-apply(scores, 2, max) print("Maximum Score per Subject:") print(col_max) Executing the above code outputs the following result: ```text "Score Matrix:" Math English programmingZhang San 88 90 85Li Si 92 88 91Wang Wu 76 82 78Zhao Liu 85 78 88Qian Qi 90 95 92 "Average Score per Student:"Zhang San Li Si Wang Wu Zhao Liu Qian Qi87.7 90.3 78.7 83.7 92.3 "Maximum Score per Subject:"Math English programming 92 95 92 [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func BarplotR Func Aov β†’