matrix, how tu use in r

In R, a matrix is a two-dimensional array-like structure, where each element of the matrix must be of the same mode (numeric, character, etc). To create a matrix in R, use the matrix() function:

main.r
# create a matrix with 3 rows and 2 columns
my_matrix <- matrix(c(1,2,3,4,5,6), nrow=3, ncol=2)

# print the matrix
my_matrix
126 chars
6 lines
main.r
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
60 chars
5 lines

To access elements of a matrix, use indexing similar to that of a vector, where the row and column are specified within square brackets:

main.r
# access element in the second row and first column
my_matrix[2,1]
67 chars
3 lines
main.r
[1] 2
6 chars
2 lines

Matrices can be manipulated using a variety of built-in functions and operators, including arithmetic and algebraic operations (+, -, *, %*%), transposition (t()), and subsetting functions (rowSums(), colSums(), rowMeans(), and colMeans()).

main.r
# add a scalar to the entire matrix
my_matrix + 2

# multiply entire matrix by a scalar
my_matrix * 3

# transpose matrix
t(my_matrix)

# calculate sums of rows and columns
rowSums(my_matrix)
colMeans(my_matrix)
212 chars
13 lines

Arrays can also be used to create multidimensional matrices in R, where each element has a corresponding row, column, and "layer" (or third dimension). However, the use of arrays is less common in R than matrices, due to the complexity of working with arrays.

gistlibby LogSnag