[英]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)
. 如果您将变量按名称存储在列表l
,则可以跳过定义n
而只需要执行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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.