Home > database >  Get the rownumber a variable reached the max value in a data.frame column R
Get the rownumber a variable reached the max value in a data.frame column R

Time:11-09

i need some help to find the row number that have the max value for each column

Data = data.frame(  
                    V1 = c(0.1, 0.2, 0.4, 0.7, 0.9),
                    v2 = c(0.1, 0.12, 0.41, 0.72, 0.91),
                    v3 = c(0.03, 0.13, 0.92, 0.50, 0.90))

Desired result: (Time of max value)

  V1 V2 V3
1  5  5  3

I tried this, but without sucess:

lapply(Data, function(x) (which(max(x))))

CodePudding user response:

I'd use max.col and t from base R:

max.col(t(Data))

Output:

[1] 5 5 3

The steps of this:

  1. First transpose the data:

    > t(Data)
       [,1] [,2] [,3] [,4] [,5]
    V1 0.10 0.20 0.40 0.70 0.90
    v2 0.10 0.12 0.41 0.72 0.91
    v3 0.03 0.13 0.92 0.50 0.90
    
  2. Then get the column with the maximum value for each row:

    > max.col(t(Data))
    [1] 5 5 3
    > 
    

Or apply:

apply(Data, 1, which.max)

CodePudding user response:

Simply using dplyr::across

library(dplyr)
Data %>%
  summarise(across(everything(), ~which.max(.x)))

  V1 v2 v3
1  5  5  3

Or using sapply,

sapply(Data, function(x) which.max(x))

V1 v2 v3 
 5  5  3 
  • Related