[英]A vector sorting by value in R
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) 或来自(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
and compactly, in data.frame
紧凑地在
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.