繁体   English   中英

R中按值排序的向量

[英]A vector sorting by value in R

我正在尝试对向量进行排序

a = c(12,44,53,39,2) 

预期输出是具有相关值的索引-从高到低

 3  2  4  1  5
53 44 39 12  2
`names<-`(sort(a,T),match(sort(a,T), a))
# 3  2  4  1  5 
#53 44 39 12  2 
sort(a, index.return=T, decreasing=T)$ix
# [1] 3 2 4 1 5

或来自(RichardScriven和@PierreLafortune的补全)的矩阵

do.call(rbind, sort(a, index.return=TRUE, decreasing=TRUE))[2:1,]
#     [,1] [,2] [,3] [,4] [,5]
# ix    3    2    4    1    5
# x    53   44   39   12    2

紧凑地在data.frame

data.frame(sort(a, T, index=T))
#    x ix
# 1 53  3
# 2 44  2
# 3 39  4
# 4 12  1
# 5  2  5
a = c(12,44,53,39,2)

sort(a,decreasing =TRUE)  # v1=Sorting variable as descending order
#[1] 53 44 39 12  2

match(sort(a,decreasing =TRUE),a) # v2 = Matching with previous position 
#[1] 3 2 4 1 5

df<-data.frame(v1=sort(a,decreasing =TRUE),v2=match(sort(a,decreasing =TRUE),a))

#   v1 v2
# 1 53  3
# 2 44  2
# 3 39  4
# 4 12  1
# 5  2  5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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