Skip to content
Prev 274348 / 398506 Next

high and lowest with names

On Oct 13, 2011, at 10:42 AM, Ben qant wrote:

            
Really? The intermediate, potentially large, objects seem to be  
proliferating.
1) For max (or min) I would have thought that one could have much more  
easily gathered the maximum and minimum locations with:

  which(x == max(x), arr.ind=TRUE)   # Bert Gunter's discarded  
suggestion

... and used the results as indices into x or rownames(x) or  
colnames(x). But I made no earlier comments because it did not appear  
that you had provided the swiss$Education object in a form that could  
be easily extracted for testing. I see now that setting up a similar  
object was fairly easy, but would encourage you to consider the `dput`  
function for such problem construction in the future;

dat2 <- matrix(sample(1:25, 25), 5,5)
colnames(dat2) = c('a','b','c','d','e')
rownames(dat2) = c('z','y','x','w','v')
arrns <- which(dat2 == max(dat2), arr.ind=TRUE)
 > arrns
   row col
v   5   1
 > colnames(dat2)[arrns[,2]] ; rownames(dat2)[arrns[,1]]
[1] "a"
[1] "v"

2) For display of all results with row/column labels :

rbind(dat2, rownames(dat2)[row(dat2)], colnames(dat2)[row(dat2)])

3) For display of values of "bottom five" and top five:

  dat2five <- which(dat2 <= c(dat2)[order(dat2)][5], arr.ind=TRUE)
  rbind( dat2LT5= dat2[dat2five],
           Rows = rownames(dat2)[ dat2five[,1] ],
           Cols = colnames(dat2)[ dat2five[,2] ])
#--------------
         [,1] [,2] [,3] [,4] [,5]
dat2LT5 "2"  "3"  "5"  "1"  "4"
Rows    "x"  "w"  "y"  "y"  "x"
Cols    "a"  "a"  "c"  "d"  "d"

dat2topfive <- which(dat2 >= c(dat2)[rev(order(dat2))][5], arr.ind=TRUE)
  rbind( dat2top5= dat2[dat2topfive],
           Rows = rownames(dat2)[ dat2topfive[,1] ],
           Cols = colnames(dat2)[ dat2topfive[,2] ])
#---------------
          [,1] [,2] [,3] [,4] [,5]
dat2top5 "24" "25" "23" "22" "21"
Rows     "z"  "v"  "y"  "w"  "v"
Cols     "a"  "a"  "b"  "e"  "e"
David Winsemius, MD
West Hartford, CT