Matrices and Arrays
Join our community on Telegram!
Join the biggest community of Pharma students and professionals.
In R, matrices and arrays are data structures used to store data in multiple dimensions. They are useful when working with structured data such as tables, grids, or multi-dimensional datasets. Both matrices and arrays store elements of the same data type, such as all numeric values or all character values.
A matrix is a two-dimensional data structure made up of rows and columns. It is similar to a table where each cell contains a value. Matrices are commonly used in mathematical calculations, statistics, and data analysis. You can create a matrix in R using the matrix() function. For example, matrix(1:6, nrow = 2, ncol = 3) creates a matrix with 2 rows and 3 columns filled with numbers from 1 to 6.
An array is a multi-dimensional extension of a matrix. While a matrix has only two dimensions (rows and columns), an array can have more than two dimensions. For example, you might use a three-dimensional array to represent data across rows, columns, and time periods. Arrays are created using the array() function, where you specify the data and the dimensions.
Below is a table showing the key differences and basic operations for matrices and arrays:
| Feature | Matrix | Array |
|---|---|---|
| Definition | Two-dimensional data structure | Multi-dimensional data structure |
| Dimensions | Rows and columns only | Can have two or more dimensions |
| Creation Function | matrix() |
array() |
| Example Creation | matrix(1:6, nrow=2) |
array(1:8, dim=c(2,2,2)) |
| Accessing Elements | m[1,2] (row 1, column 2) |
a[1,2,1] (row, column, layer) |
| Common Use | Mathematical and statistical operations | Multi-dimensional datasets |
Matrices support arithmetic operations just like vectors. For example, you can add, subtract, or multiply matrices of the same size. R also provides special matrix operations such as matrix multiplication using the %*% operator.
Arrays behave similarly to matrices, but they allow more complex data organization because of their multiple dimensions. They are useful in advanced data analysis, simulations, and scientific computing.
Understanding matrices and arrays is important because they help represent structured and multi-dimensional data efficiently in R. They are widely used in statistical modeling, machine learning, and numerical analysis.
