1

Let us say we have the following data frame in R:

DF <- as.data.frame.matrix(matrix(sample(1:15,15),ncol=5,nrow=3))

   V1  V2 V3 V4 V5
1  15   8  3 14  4
2  11   2  5 13  6
3   9   7 10 12  1

I'm trying to retrieve the column name of the top three values per row. I would like to get a new data frame with the following information:

1 V1 V4 V2
2 V4 V1 V5
3 V4 V3 V1

I tried by using apply and dapply but it is not working. I designed a function to use in apply but it is not working as expected. Could you give me any hint to tackle this. I think this should be of help.

Community
  • 1
  • 1
nhern121
  • 3,831
  • 6
  • 27
  • 40
  • The correct tag for R questions is data.frame, not dataframes. Please don't use the latter. – Frank Mar 14 '16 at 19:07

1 Answers1

2

We can loop through the rows (apply with MARGIN=1), get the numeric index of the elements in the row decreasingly with order, use that to order the column names, get the first 3 elements with head, transpose the output and convert to data.frame.

 as.data.frame(t(apply(DF, 1, function(x) 
   head(names(DF)[order(-x)],3))), stringsAsFactors=FALSE)
#  V1 V2 V3
#1 V1 V4 V2
#2 V4 V1 V5
#3 V4 V3 V1
akrun
  • 874,273
  • 37
  • 540
  • 662