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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.