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

apply()

apply runs a function across every row or every column of a table, like a teacher totaling each student's row of scores. You choose rows or columns and the tool does the rest.

In this page:

  1. apply()
Syntax
r
apply(X, MARGIN, FUN)    # MARGIN: 1 = rows, 2 = columns

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Swapping MARGIN, using 1 when columns were intended and 2 when rows were intended.
  2. Using apply() on a data frame with text and numbers, which converts everything to characters.
  3. Expecting apply() to always return a vector, when it can return a matrix or list depending on the function.
🔒

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.