如何提取每行中最大三个数字对应的矩阵?

时间:2017-02-23 07:58:47

标签: r matrix

我有一个像这样的矩阵:

x <- matrix(rnorm(100), nrow = 10)
colnames(x) <- combn(letters[1:8], 2, FUN = paste0, collapse = '')[seq_len(ncol(x))]

我想提取每行中最大的三个数字对应的colnames。我尝试使用以下代码来解决这个问题:

apply(x,1,function(x) order(x,decreasing=T)[1:3])

apply(x,1,function(x) x[order(x,decreasing=T)[1:3]])

但是我只提取值或列号,而不是colnames.Futher,如果我想在3×10矩阵的单元格中的值和列号,以及每个像这样的单元格:(值,它的colname),如何我应该改进我的代码吗?

1 个答案:

答案 0 :(得分:2)

您在申请电话中呼叫值,而不是姓名。

使用

t(apply(x,1,function(x) names(x[order(x, decreasing = T)])[1:3]))

获取

     [,1] [,2] [,3]
 [1,] "ac" "ae" "bc"
 [2,] "ah" "ae" "bd"
 [3,] "ab" "ad" "ah"
 [4,] "ah" "ae" "ag"
 [5,] "bc" "ac" "ab"
 [6,] "ad" "be" "ah"
 [7,] "ag" "be" "ah"
 [8,] "be" "bd" "ag"
 [9,] "ae" "ad" "bc"
[10,] "ac" "ad" "bc"

要合并值和合欢名,请执行以下操作:

mymatrix <- t(matrix(paste(apply(x,1,function(x) x[order(x,decreasing=T)[1:3]]), 
                      apply(x,1,function(x) names(x[order(x, decreasing = T)])[1:3]),
                      sep = ", "), nrow = 3))

输出:

     [,1]                    [,2]                    [,3]                   
 [1,] "1.59913311795783, ac"  "0.885534156178676, ae" "0.875246820694047, bc"
 [2,] "1.88262373384617, ah"  "0.872567862286068, ae" "0.660631089010629, bd"
 [3,] "1.49244514568881, ab"  "1.35311293758955, ad"  "0.394056724464136, ah"
 [4,] "2.32470081848151, ah"  "1.50673571308499, ae"  "0.447576219573032, ag"
 [5,] "1.51100753431057, bc"  "0.977989261628962, ac" "0.943834483720892, ab"
 [6,] "1.73431308924992, ad"  "1.19278829328726, be"  "0.718634846412602, ah"
 [7,] "0.930041809046426, ag" "0.800971669579496, be" "0.35523503674387, ah" 
 [8,] "0.759183586558264, be" "0.284400004143193, bd" "0.16139357971149, ag" 
 [9,] "1.45860700391869, ae"  "0.767188128292325, ad" "0.760496361266797, bc"
[10,] "1.89419796606409, ac"  "1.1554236572704, ad"   "0.850762486867097, bc"