简体   繁体   中英

Finding vectors with highest values in R

I have a series of vectors:

aaa<-11
bbb<-23
ccc<-24
ddd<-26
eee<-89
fff<-89
ggg<-100

How can I identify all variables that are equal to or exceed the second largest number? In the example above, ideal results would be:

  ggg    eee    fff 
  100    89     89   

Assuming you had a list of variable names:

n <- c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg")

You could get all their values:

vals <- unlist(mget(n))

You could then find the second largest value:

(second.largest <- sort(vals, decreasing=TRUE)[2])
# eee 
#  89 

and then grab the values that are at least that large:

vals[vals >= second.largest]
# eee fff ggg 
#  89  89 100 

If you instead had the variables stored by name in a list l , you could skip defining n and just do vals <- unlist(l) .

Or you could also do this

a = mget(c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"))
b = do.call(data.frame, a)
out = b[b %in% unique(t(b[order(b, decreasing =T)]))[1:2]]

#> out
#  eee fff ggg
#1  89  89 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM