The apply() Family (Preview)
The apply family is a set of tools that run a function over many items at once, like a teacher marking every paper with the same rules. This lesson gives you a first look at them.
In this page:
Syntax
apply(matrix_name, MARGIN, FUN)
lapply(x, FUN)
sapply(x, FUN)
The apply() Family (Preview)
R's apply family of functions (apply, lapply, sapply, and others) applies a function across the elements of a data structure without writing an explicit loop, and is covered in depth in a later chapter.
apply(m, 1, sum) applies sum across each row of a matrix. This preview introduces the concept before the dedicated Apply Family chapter goes deeper.
Note:
The second argument to apply(), 1 or 2, controls whether the function is applied by row or by column of a matrix.
Example: The apply() Family (Preview)
m <- matrix(1:6, nrow = 2)
row_sums <- apply(m, 1, sum)
col_sums <- apply(m, 2, sum)
print(row_sums)
print(col_sums)
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
- Using
apply(m, 1, sum)for rows and2for columns the wrong way round, so the results are swapped. - Using
applyon a data frame with mixed types, which converts it to a character matrix. - Expecting
sapplyandlapplyto give the same type, whenlapplyalways returns a list.
Chapter Summary
- Matrices, arrays, lists, data frames, and factors are R's main data structures.
- Data frames hold tabular data, and lists can hold mixed types.
which()finds positions, andapply()functions are previewed for working across structures.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: