← Back to R Course | Chapter 11: Apply Family | Lesson 1 of 6

apply()

In this page:

  1. apply()

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()

markup
m <- matrix(1:6, nrow = 2)

row_totals <- apply(m, 1, sum)
col_totals <- apply(m, 2, sum)

print(row_totals)
print(col_totals)
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.