如何根据扇区和子部门对数据进行排序?

时间:2016-06-30 17:52:04

标签: r sorting

我想根据扇区x和子部门sec对数据ssec(此处:1:12)进行排序。下面是一个示例,说明如何做到这一点。问题是这是否可以更优雅地完成(可能使用base-R函数/不使用其他软件包)?

## Data
set.seed(17)
(sec <- sample(rep(LETTERS[1:3], each = 4))) # 3 sectors
(ssec <- rep(sample(1:4, 12, replace = TRUE))) # 4 subsectors
x <- 1:12 # data to sort according to increasing sectors and subsectors

## Sort according to sectors
ord <- order(sec)
x. <- x[ord]
sec. <- sec[ord]
ssec. <- ssec[ord]

## Sort according to subsectors
usec. <- unique(sec.)
x.. <- x.
ssec.. <- ssec.
for(grp in usec.) {
    ii <- sec. == grp # indices of components in that sector
    ord. <- order(ssec.[ii])
    x..[ii] <- x.[ii][ord.]
    ssec..[ii] <- ssec.[ii][ord.]
}

## Result
x..
sec.
ssec..

1 个答案:

答案 0 :(得分:1)

来自order R的base函数也接受多个参数。来自?order

  

order返回一个排列,将其第一个参数重新排列为   升序或降序,通过进一步的论证打破联系。

为了演示,我们可以检查order(sec, ssec)如何对扇区和子扇区进行排序

以下是原始secssec

sec
 [1] "B" "C" "A" "B" "A" "B" "C" "C" "C" "A" "B" "A"
ssec
 [1] 3 1 3 2 1 2 4 1 3 2 1 4

应用有序索引后,sec按字母顺序排序,ssec在每秒内排序,这意味着索引order(sec, ssec)是预期的排序索引:

sec[order(sec, ssec)]
 [1] "A" "A" "A" "A" "B" "B" "B" "B" "C" "C" "C" "C"
ssec[order(sec, ssec)]
 [1] 1 2 3 4 1 2 2 3 1 1 3 4