Reputation: 43
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
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.
set.seed(24)
df1 <- as.data.frame(matrix(rnorm(100*10), ncol=10))
Upvotes: 3
Reputation: 3587
Another approach using @akrun's df1
df1$index_col <- apply(df1[,6:10],1,which.min)+5
Upvotes: 2