一种选择是使用order()
然后使用它来子集列名,例如:
set.seed(1)
df <- data.frame(matrix(runif(600*10), ncol = 600))
foo <- function(x, names) {
ord <- order(x, decreasing = TRUE)[1:5]
names[ord]
}
nams <- colnames(df)
apply(df, 1, foo, names = nams)
生产
> apply(df, 1, foo, names = nams)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "X369" "X321" "X348" "X415" "X169" "X258" "X55" "X182" "X99" "X78"
[2,] "X42" "X295" "X563" "X173" "X377" "X31" "X246" "X353" "X259" "X384"
[3,] "X98" "X440" "X371" "X207" "X429" "X292" "X433" "X437" "X123" "X558"
[4,] "X13" "X193" "X396" "X78" "X543" "X228" "X211" "X2" "X583" "X508"
[5,] "X35" "X364" "X249" "X33" "X388" "X405" "X458" "X252" "X569" "X456"
检查这是否有效:
> names(sort(unlist(df[1,, drop = TRUE]), decreasing = TRUE)[1:5])
[1] "X369" "X42" "X98" "X13" "X35"
> names(sort(unlist(df[2,, drop = TRUE]), decreasing = TRUE)[1:5])
[1] "X321" "X295" "X440" "X193" "X364"
似乎还可以。