Open In App

Get the position of the maximum element in each Row of a Matrix in R Programming – max.col() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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:




# R program to find positions 
# of maximum elements of a matrix
  
# Creating matrices
m1 <- matrix(c(1:4), 2)
m2 <- matrix(c(4, 1, 2, 3), 2)
m3 <- matrix(c(1:9), 3, 3)
  
# Calling max.col() function
max.col(m1)
max.col(m2)
max.col(m3)


Output:

[1] 2 2
[1] 1 2
[1] 3 3 3

Example 2:




# R program to find positions 
# of maximum elements of a matrix
  
# Creating matrices
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
  
# Calling max.col() function
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


Last Updated : 16 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads