R Matrices
kodingwindow@kw:~$ R ... Matrix creation > matrix1 = matrix(1:9,nrow = 3,ncol = 3) > matrix2 = matrix(1:9,nrow = 3,ncol = 3) Addition > matrix3 = matrix1 + matrix2 > matrix3 [,1] [,2] [,3] [1,] 2 8 14 [2,] 4 10 16 [3,] 6 12 18 Subtraction > matrix3 = matrix1 - matrix2 > matrix3 [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 0 0 [3,] 0 0 0 Division > matrix3 = matrix1 / matrix2 > matrix3 [,1] [,2] [,3] [1,] 1 1 1 [2,] 1 1 1 [3,] 1 1 1 Multiplication > matrix3 = matrix1 %*% matrix2 > matrix3 [,1] [,2] [,3] [1,] 30 66 102 [2,] 36 81 126 [3,] 42 96 150 Transpose of a matrix > matrix2 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > matrix3 = t(matrix2) > matrix3 [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 > matrix3[3,3] [1] 9 > matrix3[1,2] [1] 2 Substitution of a number > matrix3[1,1] = 100 > matrix3 [,1] [,2] [,3] [1,] 100 2 3 [2,] 4 5 6 [3,] 7 8 9 > matrix3[,2] = 100 > matrix3 [,1] [,2] [,3] [1,] 100 100 3 [2,] 4 100 6 [3,] 7 100 9 > matrix3[,2:3] = 24 > matrix3 [,1] [,2] [,3] [1,] 100 24 24 [2,] 4 24 24 [3,] 7 24 24 Matrix with four rows > matrix(c(1,2,3,4,5,6,7,8,9,10,11,12),nrow = 4) [,1] [,2] [,3] [1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12 Matrix with three rows and four columns > matrix(c(1,2,3,4,5,6,7,8,9,10,11,12),nrow = 3,ncol = 4) [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 > matrix(1:50,ncol = 10) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 6 11 16 21 26 31 36 41 46 [2,] 2 7 12 17 22 27 32 37 42 47 [3,] 3 8 13 18 23 28 33 38 43 48 [4,] 4 9 14 19 24 29 34 39 44 49 [5,] 5 10 15 20 25 30 35 40 45 50 > matrix(1:50,ncol = 10) + 100 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 101 106 111 116 121 126 131 136 141 146 [2,] 102 107 112 117 122 127 132 137 142 147 [3,] 103 108 113 118 123 128 133 138 143 148 [4,] 104 109 114 119 124 129 134 139 144 149 [5,] 105 110 115 120 125 130 135 140 145 150
What Next?
R Data Frames
Advertisement