R return the index of the minimum column for each row

后端 未结 2 1176
面向向阳花
面向向阳花 2020-12-16 16:12

I have a data.frame that contains 4 columns (given below). I want to find the index of the minimum column (NOT THE VALUE) for each row. Any idea hiw to achieve that?

<
相关标签:
2条回答
  • 2020-12-16 16:18

    Your English description suggests you want:

     apply( df, 1, which.min)
    

    But the answer you give is not formatted as a vector and is not the correct answer if the above interpretation is correct. Oh wait, you were expecting rownumbers.

     as.matrix(apply( d, 1, which.min))
    
       [,1]
    1     1
    2     4
    3     3
    4     3
    5     1
    6     1
    7     2
    8     2
    9     4
    10    4
    11    1
    12    3
    13    1
    14    1
    15    3
    16    3
    17    2
    18    3
    19    2
    20    4
    
    0 讨论(0)
  • 2020-12-16 16:38

    Another option is max.col of d multiplied by -1

    max.col(-d)
    # [1] 1 4 3 3 1 1 2 2 4 4 1 3 1 1 3 3 2 3 2 4
    

    If you need a matrix as output, use

    cbind(1:nrow(d),    # row
          max.col(-d))  # column position of minimum
    

    Here is a benchmark of the two approaches

    set.seed(42)
    dd <- as.data.frame(matrix(runif(1e5 * 100), nrow = 1e5, ncol = 100))
    
    library(microbenchmark)
    library(ggplot2)
    
    b <- microbenchmark(
      apply = apply(dd, 1, which.min),
      max_col = max.col(-dd),
      times = 25
    )
    
    autoplot(b)
    

    b
    #Unit: milliseconds
    #    expr      min       lq     mean   median       uq       max neval cld
    #   apply 705.7478 855.7112 906.2340 892.3214 933.4655 1211.5016    25   b
    # max_col 162.8273 175.6363 227.1156 206.0213 225.2973  406.9124    25  a 
    
    0 讨论(0)
提交回复
热议问题