Jaikumar S
Jaikumar S

Reputation: 144

How to find the second, third and nth maximum row in R with more than 10 variables?

I have a dataset with 20 variables out of which I need to use 10 variables to find the first ,second, 3rd.....nth maximum .

The variables are x1 to x10

x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
 1  2  0  3  4  5  6  7  8   5
 2  1  5  4  6  4  2  1  0   3

My expected output should be:

max1 max2 max3 max4 max5 max6 max7 max8 max9 max10
  x9   x8   x7   x6  x10   x5   x4   x2   x1    x3 
  x5   x3   x4   x6  x10   x1   x7   x2   x8    x9

I have 100 observation. The sample I provided is only one row.

Upvotes: 1

Views: 128

Answers (1)

user3710546
user3710546

Reputation:

Based on etienne's comment, but will be inefficient for large dataset.

foo <- function(x){
  y <- order(x, decreasing = TRUE)
  y <- paste0("x", y)
}
t(apply(dat, 1, foo))
#      [,1] [,2] [,3] [,4] [,5]  [,6] [,7] [,8] [,9] [,10]
# [1,] "x9" "x8" "x7" "x6" "x10" "x5" "x4" "x2" "x1" "x3" 
# [2,] "x5" "x3" "x4" "x6" "x10" "x1" "x7" "x2" "x8" "x9" 

Upvotes: 3

Related Questions