Introduction
Applying functions on matrices helps you quickly calculate values like sums or averages for rows or columns without writing loops.
apply(X, MARGIN, FUN, ...) # X: matrix or array # MARGIN: 1 for rows, 2 for columns # FUN: function to apply # ...: additional arguments to FUN
mat <- matrix(1:6, nrow=2) apply(mat, 1, sum)
mat <- matrix(1:6, nrow=2) apply(mat, 2, mean)
mat <- matrix(1:9, nrow=3) apply(mat, 1, max)
mat <- matrix(c(4, 7, 2, 9, 5, 1), nrow=2) row_sums <- apply(mat, 1, sum) col_means <- apply(mat, 2, mean) print(row_sums) print(col_means)
apply() function do when used on a matrix?apply() function is designed to run a function on margins of an array or matrix.apply() runs the function on each row or column.m using apply() in R?apply(), margin 2 means columns.apply(m, 2, sum).m <- matrix(1:6, nrow=2) apply(m, 1, max)
m is created with values 1 to 6, 2 rows:
Row 1: 1, 3, 5
Row 2: 2, 4, 6m <- matrix(1:9, nrow=3) apply(m, 3, mean)
m has 2 dimensions (rows and columns).m of numeric values. You want to create a new vector that contains the mean of each row but only for rows where the sum is greater than 10. Which R code correctly does this using apply()?[!is.na(.)], giving only desired means.Pass the test and this pattern moves unknown