Search code examples
rmatrixminimum

How to find the indexes of minimum value for each row of a dataframe?


Assume I have a dataframe df like

  [,1] [,2] [,3] [,4]
x    1    2    7    1
y    1    5    1    5

I would like to find the indexes of minimum value for each row of df. My expected result is

YES NO NO  NO YES
YES NO YES NO No

I tried

x <- c(1, 2, 7, 1)
y <- c(1, 5, 1, 5)
df <- rbind(x, y)
apply(df, 1, which.min)

but it does not work. Could you please elaborate on how to do so?


Solution

  • We can use apply to loop over the rows (MARGIN =1), compare the elements in the row with min of the row

    t(apply(df, 1, function(x) x == min(x)))
    

    -output

    #  [,1]  [,2]  [,3]  [,4]
    #x TRUE FALSE FALSE  TRUE
    #y TRUE FALSE  TRUE FALSE
    

    Or make it compact with rowMins from matrixStats

    library(matrixStats)
    df == rowMins(df)
    #  [,1]  [,2]  [,3]  [,4]
    #x TRUE FALSE FALSE  TRUE
    #y TRUE FALSE  TRUE FALSE
    

    Or if we want to stick with base R and use a vectorized option then pmin is another way (after converting the matrix to data.frame)

    df == do.call(pmin, as.data.frame(df))