如何获得具有前10个最高值的变量的列名?

时间:2013-05-14 19:26:27

标签: r dataframe

如果我有一个包含600列(变量)的data.frame(sum_clus)和没有NA并且都是数值的10行,我怎样才能创建5个新变量,这些变量为我提供前5个变量的列名在那一排?

例如。

max <- apply(sum_clus ,1, max)    
for(ii in 1:10) sum_clus$max[ii] <- colnames(sum_clus)[which(sum_clus[ii , ] 
== sum_clus[ii, sum_clus[ii,] == max[ii]])]

上面的代码帮助我创建了一个变量sum_clus $ max,它给出了每行中max变量的列名。同样,我怎样才能获得5个这样的变量,它们给出了前5个变量的列名? sum_clus $ max,sum_clus $ second_but_max等等..

提前致谢!

2 个答案:

答案 0 :(得分:5)

一种选择是使用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"

似乎没问。

答案 1 :(得分:3)

这是一个类似的解决方案,使用(i)循环而不是apply; (ii)rank代替order

set.seed(1)
n_i   = 10
n_ii  = 600
n_top = 5
df <- data.frame(matrix(runif(n_ii*n_i), ncol = n_ii))

out <- matrix("",n_top,n_i)
for (i in 1:n_i){
    colranks <- rank(df[i,])
    out[,i] <- names(sort(colranks)[n_ii:(n_ii-(n_top-1))])
}
#      [,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"

apply的单线模拟

apply(df,1,function(x)names(sort(rank(x))))[600:596,]