In R, a matrix is a two-dimensional data structure consisting of rows and columns. It is created using the matrix() function and can store elements of the same data type such as numbers, characters, or logical values. Matrices in R are often used for various mathematical operations, data manipulation, and statistical analysis.
Here's an example of creating a matrix in R:
# Create a matrix
my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
# Print the matrix
print(my_matrix)
Output:
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
In the example above, we created a 2x3 matrix named my_matrix with elements from 1 to 6 arranged in row-major order. The nrow parameter specifies the number of rows, and the ncol parameter specifies the number of columns.
Matrices in R provide a convenient way to perform mathematical operations, apply functions across rows or columns, and perform matrix-specific computations. They are commonly used in linear algebra, statistical modeling, and data analysis tasks.