Get the position of the maximum element in each Row of a Matrix in R Programming – max.col() Function
Last Updated :
16 Jun, 2020
max.col()
function in R Language check for maximum value in each row and returns the column no. for it.
Syntax: max.col(x, ties.method)
Parameters:
x: Numeric matrix
ties.method: It takes random, first, and last as value and returns the position accordingly in case of a tie.
Example 1:
m1 < - matrix(c( 1 : 4 ), 2 )
m2 < - matrix(c( 4 , 1 , 2 , 3 ), 2 )
m3 < - matrix(c( 1 : 9 ), 3 , 3 )
max .col(m1)
max .col(m2)
max .col(m3)
|
Output:
[1] 2 2
[1] 1 2
[1] 3 3 3
Example 2:
m1 < - matrix(c( 2 , 3 , 2 , 4 ), 2 )
m2 < - matrix(c( 2 , 3 , 2 , 4 ), 2 )
m3 < - matrix(c( 2 , 3 , 2 , 4 ), 2 )
m1
max .col(m1, ties.method = "random" )
max .col(m2, ties.method = "first" )
max .col(m3, ties.method = "last" )
|
Output:
[, 1] [, 2]
[1, ] 2 2
[2, ] 3 4
[1] 2 2
[1] 1 2
[1] 2 2
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...