I'm trying to sort a vector where
a = c(12,44,53,39,2)
Expected output is index with its associated values - high to low
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
Or in matrix from (compliments of @RichardScriven and @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
and compactly, in 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
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.