0
0
R Programmingprogramming~5 mins

Apply functions on matrices in R Programming

Choose your learning style9 modes available
Introduction
Applying functions on matrices helps you quickly calculate values like sums or averages for rows or columns without writing loops.
You want to find the sum of each row in a table of numbers.
You need the average value of each column in a data set.
You want to apply a custom calculation to every row or column.
You want to check the maximum or minimum value in each row or column.
Syntax
R Programming
apply(X, MARGIN, FUN, ...)

# X: matrix or array
# MARGIN: 1 for rows, 2 for columns
# FUN: function to apply
# ...: additional arguments to FUN
Use MARGIN = 1 to apply the function to each row.
Use MARGIN = 2 to apply the function to each column.
Examples
Sum of each row in the matrix.
R Programming
mat <- matrix(1:6, nrow=2)
apply(mat, 1, sum)
Average of each column in the matrix.
R Programming
mat <- matrix(1:6, nrow=2)
apply(mat, 2, mean)
Maximum value in each row.
R Programming
mat <- matrix(1:9, nrow=3)
apply(mat, 1, max)
Sample Program
This program creates a 2x3 matrix, calculates the sum of each row and the average of each column, then prints the results.
R Programming
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)
OutputSuccess
Important Notes
The apply function returns a vector or array depending on the function and margin.
You can use any function that works on a vector, like sum, mean, max, min, or your own custom function.
If you want to apply functions on higher dimensions, you can use arrays with apply.
Summary
Use apply() to run a function on rows or columns of a matrix easily.
Set MARGIN to 1 for rows, 2 for columns.
Great for quick calculations like sums, means, or max values.