Matrices or commonly known as a matrix are combinations of data objects arranged in columns and rows - The values contained in a matrix can span the entire atomic objects used within R - Matrices are vectors with dimension attributes and dimensions are integer vectors within itself - The integer value within a basic matrix is 2x2 2 columns and 2 rows produce the dimensions needed - The first method we will produce a empty matrix - m <- matrix(nrow = 2, ncol = 3) m [,1] [,2] [,3] [1,] NA NA NA [2,] NA NA NA As noticed with the above example there are no values contained within this newly created matrices and this it will be represented by the designated value of NA or non-applicable, and when dealing with an unknown matrix one could use the function dim() to get the dimensions of the matrix - dim(m) 2 3 The first value of the dim() function is the number of columns and the second represents the number of rows - Another example to find the attributes of a variable "m" would be to use the function attributes() which will help identify the use of "m" - attributes(m) $dim [1] 2 3 This function reveals that the variable "m" is being used as a matrix by the designation of "$dim" which stands for dimension - Only matrix have dimensions and as well attributes() just as the dim() function displays the dimension values of 2 columns and 3 rows - Another way to produce a matrix is to fill it with data from the function its self - m <- matrix(1:9, nrow = 3, ncol = 3) print(m) [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 dim(m) [1] 3 3 attributes(m) $dim [1] 3 3 Another method for producing a matrix is to use the dim() function and concatenate two values into the dim() function as depicted below - m <- 1:25 dim(m) <- c(5,5) print(m) [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 dim(m) [1] 5 5 attributes(m) $dim [1] 5 5 As seen from previous examples how the dim() and attributes() functions can be useful when dealing with unknown matrices - Another method to create a matrix is to use cbind() "column-bind" and or rbind() "row-bind" functions - This can be one of the more easier to follow examples and is why it is saved for the last example - It should be very clear how and what one must do, however examples only ensure the full understanding - c <- 1:10 r <- 11:20 cbind(c,r) [1,] 1 11 [2,] 2 12 [3,] 3 13 [4,] 4 14 [5,] 5 15 [6,] 6 16 [7,] 7 17 [8,] 8 18 [9,] 9 19 [10,] 10 20 rbind(c,r) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 With the examples above one can start to understand their usefulness and ease of creation with the proper knowledge involved - |

Programming and Analysis > R GNU S >