我想对包含评分的向量进行排序,
r<-c("A","AA","AAA","BBB","BB","B","CCC")
但是,通过应用sort
> sort(r)
[1] "A" "AA" "AAA" "B" "BB" "BBB" "CCC"
有什么方法可以使我获得以下信息
"AAA" "AA" "A" "BBB" "BB" "B" "CCC"
答案 0 :(得分:2)
您需要使用因子并按如下所示创建级别:
r<-c("A","AA","AAA","BBB","BB","B","CCC")
r <- factor(r, levels = c("AAA", "AA","A","BBB","BB","B","CCC"))
sort(r)
答案 1 :(得分:1)
r <- c("A","AA","AAA","BBB","BB","B","CCC")
r <- factor(r, levels = c("AAA","AA","A","BBB", "BB", "B", "CCC"))
sort(r)
# [1] AAA AA A BBB BB B CCC
答案 2 :(得分:1)
带有ave
ave(r, substr(r, 1, 1), FUN = function(x) sort(x, decreasing = TRUE))
#[1] "AAA" "AA" "A" "BBB" "BB" "B" "CCC"