sahil_singhal
sahil_singhal

Reputation: 43

How to return the index of a column containing minimum value in a dataframe in R

Suppsoe I have a 100X10 dataframe. For each row, I want to add an extra column which contains the column number containing the minimum value. Also this function to be applied only for specific columns say column No. 6 to 10.

Upvotes: 2

Views: 570

Answers (2)

akrun
akrun

Reputation: 887118

We can use max.col

transform(df1, newCol = (max.col(-1*df1[6:10], "first"))+5)

NOTE: The max.col approach would be very fast compared to any loop or apply based approach.

data

set.seed(24)
df1 <- as.data.frame(matrix(rnorm(100*10), ncol=10))

Upvotes: 3

user2100721
user2100721

Reputation: 3587

Another approach using @akrun's df1

df1$index_col <- apply(df1[,6:10],1,which.min)+5

Upvotes: 2

Related Questions