0

I have 1 row with 20 columns which is having numeric data. Now i want to find out the 3 column name which is having the maximum value in single row in descending order.

dd <- data.frame(a=10,b=45,c=67,d=32,e=5,f=46,g=23,h=65,i=87,j=43)

 a  b  c  d e  f  g  h  i  j
10 45 67 32 5 46 23 65 87 43 

I tried this

max.col(dd) 

but i am getting only single value. I want to find 3 max column name/number

Jaap
  • 81,064
  • 34
  • 182
  • 193
Monty
  • 129
  • 2
  • 10

2 Answers2

2

One way with dplyr and tidyr:

library(dplyr)
library(tidyr)

dd %>% 
  gather() %>% 
  top_n(3) %>% 
  arrange(desc(value))

# A tibble: 3 x 2
  key   value
  <chr> <dbl>
1 i      87.0
2 c      67.0
3 h      65.0
tyluRp
  • 4,678
  • 2
  • 17
  • 36
2

That's it. No package required.

dd[,apply(dd, 1, function(x) order(x, decreasing = T)[1:3])]
   i  c  h
1 87 67 65
YOLO
  • 20,181
  • 5
  • 20
  • 40