在R中的矩阵中对行和列进行排序

时间:2015-04-27 11:10:54

标签: r matrix

我有以下矩阵:

          [,1]     [,2]     [,3]     [,4] 
 [1,] 2275.351 2275.351 2275.351 2275.351 
 [2,] 2269.562 2269.562 2269.562 2269.562
 [3,] 1925.700 1925.700 1925.700 1925.700 
 [4,] 1904.195 1904.195 1904.195 1904.195 
 [5,] 1974.039 1974.039 1974.039 1974.039 

我想对这个矩阵进行排序,以便制作以下矩阵。

          [,1]     [,2]     [,3]     [,4] 
 [1,] 1904.195 1904.195 1904.195 1904.195 
 [2,] 1925.700 1925.700 1925.700 1925.700
 [3,] 1974.039 1974.039 1974.039 1974.039 
 [4,] 2269.562 2269.562 2269.562 2269.562
 [5,] 2275.351 2275.351 2275.351 2275.351

任何人都有优雅的r代码?

此致

2 个答案:

答案 0 :(得分:0)

你的问题并不明确。这取决于你希望如何排序。您是否独立对每列进行排序?或者你是否对所有的价值进行排序并将他们安排在一个主要的时代?或者你按照第一个顺序对所有列进行排序?

# Read your data
x <- matrix(scan(text = "
2275.351 2275.351 2275.351 2275.351
2269.562 2269.562 2269.562 2269.562
1925.700 1925.700 1925.700 1925.700
1904.195 1904.195 1904.195 1904.195
1974.039 1974.039 1974.039 1974.039"), byrow = TRUE, ncol = 4)


# Sort all entries in a row-major order:
A <- matrix(sort(t(x)), nrow = nrow(x), byrow = TRUE)
print(A)

# Sort each column
B <- apply(x, 2, sort)
print(B)

答案 1 :(得分:0)

a[do.call(order, lapply(1:NCOL(a), function(i) a[, i])), ]
           V1       V2       V3       V4
[1,] 1904.195 1904.195 1904.195 1904.195
[2,] 1925.700 1925.700 1925.700 1925.700
[3,] 1974.039 1974.039 1974.039 1974.039
[4,] 2269.562 2269.562 2269.562 2269.562
[5,] 2275.351 2275.351 2275.351 2275.351