Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 64
4.3.4.1 Creating Matrices
ОглавлениеA matrix is in two-dimensional data set where all elements are of the same type. The matrix()
function offers a convenient way to define it:
matrix()
# Create a matrix. M = matrix( c(1:6), nrow = 2, ncol = 3, byrow = TRUE) print(M) ## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 4 5 6 M = matrix( c(1:6), nrow = 2, ncol = 3, byrow = FALSE) print(M) ## [,1] [,2] [,3] ## [1,] 1 3 5 ## [2,] 2 4 6
It is also possible to create a unit or zero vector with the same function. If we supply one scalar instead a vector to the first argument of the function matrix()
, it will be recycled as much as necessary.
matrix()
# Unit vector: matrix (1, 2, 1) ## [,1] ## [1,] 1 ## [2,] 1 # Zero matrix or vector: matrix (0, 2, 2) ## [,1] [,2] ## [1,] 0 0 ## [2,] 0 0 # Recycling also works for shorter vectors: matrix (1:2, 4, 4) ## [,1] [,2] [,3] [,4] ## [1,] 1 1 1 1 ## [2,] 2 2 2 2 ## [3,] 1 1 1 1 ## [4,] 2 2 2 2 # Fortunately, R expects that the vector fits exactly n times in the matrix: matrix (1:3, 4, 4) ## Warning in matrix(1:3, 4, 4): data length [3] is not a sub-multiple or multiple of the number of rows [4] ## [,1] [,2] [,3] [,4] ## [1,] 1 2 3 1 ## [2,] 2 3 1 2 ## [3,] 3 1 2 3 ## [4,] 1 2 3 1 # So, the previous was bound to fail.