使用非唯一列表对向量进行排序,然后按字母顺序

问题描述 投票:0回答:1

假设两个向量

a <- c("AA", "BA", "BB", "AB", "AC", "BC")
b <- c(2, 1, 1, 1, 1, 2)

我想按

a
订购
b
,但显然存在很多可能性,因为
b
具有非唯一元素。所以,我的进一步限制是按字母顺序排列

c("AB", "AC", "BA", "BB", "AA", "BC")

这可能吗?

r sorting
1个回答
0
投票

先按 b 排序,然后按 a 排序。

> a[order(b, a)]
[1] "AB" "AC" "BA" "BB" "AA" "BC"
> cbind(a, b, a[order(b, a)])
     a    b       
[1,] "AA" "2" "AB"
[2,] "BA" "1" "AC"
[3,] "BB" "1" "BA"
[4,] "AB" "1" "BB"
[5,] "AC" "1" "AA"
[6,] "BC" "2" "BC"
© www.soinside.com 2019 - 2024. All rights reserved.