In R, you can find the maximum and minimum values in each row or column of a matrix using the apply()
function. This function allows you to apply a function to the rows or columns of a matrix.
In this example,
mat
.apply()
function to find the maximum value in each row of the matrix mat
. We set the second argument of apply()
to 1
to indicate that the function should be applied to rows.max
function is used as the third argument of apply()
to find the maximum values.row_max
.row_max
to the console to display the maximum values in each row.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
row_max <- apply(mat, 1, max)
print(row_max)
[1] 3 6
In this example,
mat
.apply()
function to find the maximum value in each column of the matrix mat
. We set the second argument of apply()
to 2
to indicate that the function should be applied to columns.max
function is used as the third argument of apply()
to find the maximum values.col_max
.col_max
to the console to display the maximum values in each column.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
col_max <- apply(mat, 2, max)
print(col_max)
[1] 4 5 6
In this example,
mat
.apply()
function to find the minimum value in each row of the matrix mat
. We set the second argument of apply()
to 1
to indicate that the function should be applied to rows.min
function is used as the third argument of apply()
to find the minimum values.row_min
.row_min
to the console to display the minimum values in each row.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
row_min <- apply(mat, 1, min)
print(row_min)
[1] 1 4
In this example,
mat
.apply()
function to find the minimum value in each column of the matrix mat
. We set the second argument of apply()
to 2
to indicate that the function should be applied to columns.min
function is used as the third argument of apply()
to find the minimum values.col_min
.col_min
to the console to display the minimum values in each column.mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
col_min <- apply(mat, 2, min)
print(col_min)
[1] 1 2 3
In this tutorial, we learned How to Find Row and Column Max/Min in R language with well detailed examples.