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:
Syntax
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()
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
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
- Swapping
MARGIN, using1when columns were intended and2when rows were intended. - Using
apply()on a data frame with text and numbers, which converts everything to characters. - Expecting
apply()to always return a vector, when it can return a matrix or list depending on the function.