我想根据扇区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..
答案 0 :(得分:1)
来自order
R的base
函数也接受多个参数。来自?order
:
order
返回一个排列,将其第一个参数重新排列为 升序或降序,通过进一步的论证打破联系。
为了演示,我们可以检查order(sec, ssec)
如何对扇区和子扇区进行排序
以下是原始sec
和ssec
:
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