Akira
Akira

Reputation: 2870

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?

Upvotes: 1

Views: 1058

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

A base R option using Reduce + pmin (better to use do.call (rather than Reduce) as @akrun presented when more columns are involved, from the perspective of speed since Reduce would be much slower.)

Reduce(pmin, data.frame(df)) == df

gives

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

Upvotes: 1

akrun
akrun

Reputation: 886938

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))

Upvotes: 1

Duck
Duck

Reputation: 39585

Try with

#Code
X==apply(X,1, min)

Output:

X==apply(X,1, min)
    V2    V3    V4    V5
x TRUE FALSE FALSE  TRUE
y TRUE FALSE  TRUE FALSE

Some data used:

#Data
X <- structure(c(1L, 1L, 2L, 5L, 7L, 1L, 1L, 5L), .Dim = c(2L, 4L), .Dimnames = list(
    c("x", "y"), c("V2", "V3", "V4", "V5")))

Upvotes: 2

Related Questions