The apply() Family (Preview)
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: