R Language: Matrices

0
Matrices in R are vectors with a dimension attribute. The dimension attribute is itself an integer vector of length 2 (number of rows, number of columns).

Matrices are constructed column-wise, so entries can be thought of starting in the “upper left” corner and running down the columns.

Matrices can be created in a number of ways in R. One way is to use the `matrix()` function. The `matrix()` function takes a number of arguments, including the elements of the matrix, the number of rows, and the number of columns. For example, the following code creates a matrix with the numbers 1 to 6, with 2 rows and 3 columns:

m <- matrix(1:6, nrow = 2, ncol = 3)

Another way to create matrices is to use the `cbind()` and `rbind()` functions. The `cbind()` function combines vectors by columns, and the `rbind()` function combines vectors by rows. For example, the following code creates a matrix with the numbers 1 to 3 in the first column, and the numbers 10 to 12 in the second column:

x <- 1:3
y <- 10:12
cbind(x, y)

Matrices can also be created directly from vectors by adding a dimension attribute. For example, the following code creates a matrix from the vector 1:10, with 2 rows and 5 columns:

m <- 1:10
dim(m) <- c(2, 5)

Post a Comment

0Comments
Post a Comment (0)