Q:

R sort by column values and get the column numbers

So I have a 2D array like this:
       A1BG         A1CF          A2M        A2ML1      A3GALT2
1  6.487285e-07 1.498563e-04 2.406783e-04 6.487285e-07 6.487285e-07
2  4.639610e-07 3.639610e-07 3.639610e-07 3.639610e-07 5.639610e-07
3  3.542874e-07 3.542874e-06 3.542874e-07 2.161153e-05 3.542874e-07
4  9.150830e-07 9.150830e-07 9.150830e-07 9.150830e-07 9.150830e-07
5  2.854448e-04 2.523827e-07 1.539534e-05 2.523827e-07 2.523827e-07

Trying to get the index(column names) of the largest 3 elements in each row. Ideal output would be like:
1 A2M A1CF
2 A3GALT2 A1BG 
3 A2ML1 A1CF 

A:

You could use apply and set the margin to rows, order by max value, and select the top three values.
set.seed(1)
df <- data.frame(a = rnorm(100, 100),
                 b = rnorm(100, 25),
                 d = rnorm(100, 90),
                 d = rnorm(100, 95))

output <- apply(df, 1, function(x) order(-x)[1:3])
output
> output
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    1    1    1    1    1    1    1    1
[2,]    4    4    4    4    4    4    4    4    4
[3,]    3    3    3    3    3    3    3    3    3

Will return output in matrix format.

