Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column name of the variable with the top 10 highest values?

Tags:

dataframe

r

If I have a data.frame(sum_clus) with 600 columns(variables) and 10 rows which have no NA's and are all numeric values, how can I create 5 new variables that give me the column names of the top 5 variables in that row?

For eg.

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]])]

This above code helped me create a variable sum_clus$max which gives me the column name of the max variable in each row. Similarly, how can I get 5 such variables that give me the column names of the top 5 variables? sum_clus$max, sum_clus$second_but_max, and so on..

Thanks in advance!

like image 898
Shreyes Avatar asked May 14 '13 19:05

Shreyes


2 Answers

One option is to use order() and then use that to subset the column names, e.g.:

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)

Producing

> 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"

Check this works:

> 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"

Seems OK.

like image 105
Gavin Simpson Avatar answered Oct 01 '22 20:10

Gavin Simpson


Here's a similar solution, using (i) a loop instead of apply; and (ii) rank instead of 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"

The one-liner analogue with apply is

apply(df,1,function(x)names(sort(rank(x))))[600:596,]
like image 25
Frank Avatar answered Oct 01 '22 19:10

Frank