按R

时间:2015-07-29 01:46:29

标签: r sorting vector

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

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

预期产出是指数及其相关值 - 从高到低

 3  2  4  1  5
53 44 39 12  2

3 个答案:

答案 0 :(得分:3)

`names<-`(sort(a,T),match(sort(a,T), a))
# 3  2  4  1  5 
#53 44 39 12  2 

答案 1 :(得分: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

答案 2 :(得分:1)

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