apply()
In this page:
apply()
apply(X, MARGIN, FUN) applies a function across the rows (MARGIN = 1) or columns (MARGIN = 2) of a matrix or data frame, replacing a manual loop with a single vectorized call. It returns a vector (or matrix) of results, one per row or column processed. This is the go-to function when your data is matrix-shaped and needs the same operation applied along one dimension.
Note: MARGIN = 1 means "apply by row"; MARGIN = 2 means "apply by column" -- a common source of confusion worth memorizing.
Example: apply()
m <- matrix(1:6, nrow = 2)
row_totals <- apply(m, 1, sum)
col_totals <- apply(m, 2, sum)
print(row_totals)
print(col_totals)
Login to try C/C++/Java/PHP code in the editor