0
0
R Programmingprogramming~5 mins

Matrix creation in R Programming

Choose your learning style9 modes available
Introduction
A matrix helps you organize numbers in rows and columns, like a table, so you can work with many values at once.
When you want to store data in a grid format, like a spreadsheet.
When you need to do math with rows and columns, like adding or multiplying tables of numbers.
When you want to represent images or game boards as numbers.
When you want to organize survey results or measurements in a structured way.
Syntax
R Programming
matrix(data, nrow = , ncol = , byrow = FALSE, dimnames = NULL)
data: the values to fill the matrix with, usually a vector.
nrow and ncol: number of rows and columns you want.
byrow: if TRUE, fills the matrix by rows; if FALSE (default), fills by columns.
Examples
Creates a 2-row, 3-column matrix filled column-wise with numbers 1 to 6.
R Programming
matrix(1:6, nrow = 2, ncol = 3)
Creates the same size matrix but fills it row-wise.
R Programming
matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
Creates a 2x2 matrix with specific numbers.
R Programming
matrix(c(5, 10, 15, 20), nrow = 2, ncol = 2)
Sample Program
This program creates a 3x3 matrix filled by rows with numbers 1 to 9, then prints it.
R Programming
my_matrix <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
print(my_matrix)
OutputSuccess
Important Notes
If the data vector is shorter than needed, R repeats the values to fill the matrix.
You can add names to rows and columns using the dimnames argument for easier reading.
Matrices in R always contain elements of the same type (all numbers, all characters, etc.).
Summary
A matrix is a table of values arranged in rows and columns.
Use the matrix() function with data, number of rows, and columns to create one.
You can fill the matrix by rows or by columns using the byrow argument.