简体   繁体   English

每行列名称前3个数据框R

[英]column names per row top 3 dataframe R

Let us say we have the following data frame in R: 假设我们在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. 我尝试使用apply和dapply,但无法正常工作。 I designed a function to use in apply but it is not working as expected. 我设计了一个可在apply中使用的函数,但未按预期工作。 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 . 我们可以遍历各行( applyMARGIN=1 ),使用order递减该行中元素的数字索引,使用该索引对列名进行order ,使用head获取前3个元素,转置输出并转换为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM