带有以下示例的标题应该是不言自明的:
m = unique(replicate(5, sample(1:5, 5, rep=F)), MARGIN = 2)
m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 1 4 3
[2,] 5 1 5 1 2
[3,] 4 3 3 3 1
[4,] 3 4 4 5 5
[5,] 2 2 2 2 4
但是我想要的是:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 3 4 5
[2,] 5 5 2 1 1
[3,] 3 4 1 3 3
[4,] 4 3 5 5 4
[5,] 2 2 4 2 2
理想情况下,我想找到一种方法,当列向量是单词(字母顺序)时,可以执行相同的过程。
我尝试过类似m[ , sort(m)]
之类的事情,但没有成功...
答案 0 :(得分:1)
m[, order(m[1, ])
将按第一行对列进行排序。 m[, order(m[1, ], m[2, ])]
将按第一行排序,使用第二行作为决胜局。幻想起来,m[, do.call(order, split(m, row(m)))]
将按第一行的顺序排列各列,并使用所有随后的平局。这将像character
一样处理numeric
数据。
set.seed(47)
m = replicate(5, sample(1:5, 5, rep=F))
m
# [,1] [,2] [,3] [,4] [,5]
# [1,] 5 4 1 5 1
# [2,] 2 2 3 2 3
# [3,] 3 5 5 1 2
# [4,] 4 3 2 3 5
# [5,] 1 1 4 4 4
m[, do.call(order, split(m, row(m)))]
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 1 4 5 5
# [2,] 3 3 2 2 2
# [3,] 2 5 5 1 3
# [4,] 5 2 3 3 4
# [5,] 4 4 1 4 1