Matrix in R Programming Language
Table of Content:
A matrix is a collection of data elements arranged in a two-dimensional rectangular layout. The following is an example of a matrix with 2 rows and 3 columns.
We reproduce a memory representation of the matrix in R with the matrix function. The data elements must be of the same basic type.
> A = matrix(
+ c(2, 4, 3, 1, 5, 7), # the data elements
+ nrow=2, # number of rows
+ ncol=3, # number of columns
+ byrow = TRUE) # fill matrix by rows
> A # print the matrix
[,1] [,2] [,3]
[1,] 2 4 3
[2,] 1 5 7
An element at the mth row, nth column of A can be accessed by the expression A[m, n].
> A[2, 3] # element at 2nd row, 3rd column
[1] 7
The entire mth row A can be extracted as A[m, ].
> A[2, ] # the 2nd row
[1] 1 5 7
Similarly, the entire nth column A can be extracted as A[ ,n].
> A[ ,3] # the 3rd column
[1] 3 7
We can also extract more than one rows or columns at a time.
> A[ ,c(1,3)] # the 1st and 3rd columns
[,1] [,2]
[1,] 2 3
[2,] 1 7
If we assign names to the rows and columns of the matrix, than we can access the elements by names.
> dimnames(A) = list(
+ c("row1", "row2"), # row names
+ c("col1", "col2", "col3")) # column names
> A # print A
col1 col2 col3
row1 2 4 3
row2 1 5 7
> A["row2", "col3"] # element at 2nd row, 3rd column
[1] 7