如何在 R 中使用单行代码删除矩阵的不同行和列?
任何大小矩阵的行和列的删除或添加大多是通过使用单个方括号完成的,这也是最简单的方法。要删除行和列,我们只需要使用列索引或行索引,如果我们想删除多个行或列,则可以通过在 c 中插入它们并用逗号分隔它们来实现,例如 c(-1,-2)。如果我们想按顺序删除多个行或列,则可以使用冒号。
示例
> M<-matrix(1:100,nrow=10) > M
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100
> M[-2:-3,-6:-7]
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 11 21 31 41 71 81 91 [2,] 4 14 24 34 44 74 84 94 [3,] 5 15 25 35 45 75 85 95 [4,] 6 16 26 36 46 76 86 96 [5,] 7 17 27 37 47 77 87 97 [6,] 8 18 28 38 48 78 88 98 [7,] 9 19 29 39 49 79 89 99 [8,] 10 20 30 40 50 80 90 100
> M[-1:-3,-6:-10]
输出
[,1] [,2] [,3] [,4] [,5] [1,] 4 14 24 34 44 [2,] 5 15 25 35 45 [3,] 6 16 26 36 46 [4,] 7 17 27 37 47 [5,] 8 18 28 38 48 [6,] 9 19 29 39 49 [7,] 10 20 30 40 50
> M[c(-1,-3),c(-6,-10)]
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 2 12 22 32 42 62 72 82 [2,] 4 14 24 34 44 64 74 84 [3,] 5 15 25 35 45 65 75 85 [4,] 6 16 26 36 46 66 76 86 [5,] 7 17 27 37 47 67 77 87 [6,] 8 18 28 38 48 68 78 88 [7,] 9 19 29 39 49 69 79 89 [8,] 10 20 30 40 50 70 80 90
> M[c(-5,-8),c(-2,-9)]
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 21 31 41 51 61 71 91 [2,] 2 22 32 42 52 62 72 92 [3,] 3 23 33 43 53 63 73 93 [4,] 4 24 34 44 54 64 74 94 [5,] 6 26 36 46 56 66 76 96 [6,] 7 27 37 47 57 67 77 97 [7,] 9 29 39 49 59 69 79 99 [8,] 10 30 40 50 60 70 80 100
> M[c(-5,-6:-8),c(-2,-9)]
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 21 31 41 51 61 71 91 [2,] 2 22 32 42 52 62 72 92 [3,] 3 23 33 43 53 63 73 93 [4,] 4 24 34 44 54 64 74 94 [5,] 9 29 39 49 59 69 79 99 [6,] 10 30 40 50 60 70 80 100
> M[c(-5),c(-2,-5:-9)]
输出
[,1] [,2] [,3] [,4] [1,] 1 21 31 91 [2,] 2 22 32 92 [3,] 3 23 33 93 [4,] 4 24 34 94 [5,] 6 26 36 96 [6,] 7 27 37 97 [7,] 8 28 38 98 [8,] 9 29 39 99 [9,] 10 30 40 100
> M[c(-2,-5),c(-2:-4,-5,-9)]
输出
[,1] [,2] [,3] [,4] [,5] [1,] 1 51 61 71 91 [2,] 3 53 63 73 93 [3,] 4 54 64 74 94 [4,] 6 56 66 76 96 [5,] 7 57 67 77 97 [6,] 8 58 68 78 98 [7,] 9 59 69 79 99 [8,] 10 60 70 80 100
广告