R Tutorial



R MATRICES


Matrices in R

A matrix in R is a two-dimensional data structure that contains elements of the same data type arranged in rows and columns. It is a special case of a vector.

Creating a Matrix

Use the matrix() function:

# Create a 2x3 matrix
m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)

# Output:
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
  

By default, R fills matrices column-wise.

Filling Matrix by Row

m <- matrix(1:6, nrow = 2, byrow = TRUE)
# Now elements are filled row-wise.
  

Accessing Matrix Elements

  • m[1, 2] → Element at 1st row, 2nd column
  • m[ ,2] → Entire 2nd column
  • m[1, ] → Entire 1st row

Matrix Operations

Basic operations can be done element-wise or using matrix math:

a <- matrix(1:4, nrow=2)
b <- matrix(5:8, nrow=2)

a + b      # Matrix addition
a * b      # Element-wise multiplication
a %*% b    # Matrix multiplication (dot product)
t(a)       # Transpose
  

Naming Rows and Columns

rownames(m) <- c("Row1", "Row2")
colnames(m) <- c("Col1", "Col2", "Col3")
  

This helps when accessing elements like: m["Row1", "Col2"]

Useful Functions

  • dim(m) – get dimensions (rows, cols)
  • nrow(m), ncol(m) – get row or column count
  • length(m) – total number of elements
  • sum(m), mean(m) – calculate total and average

Summary

  • Matrices are 2D arrays with same data type.
  • Use matrix() to create them.
  • Access elements using [row, column] syntax.
  • Matrix operations include addition, multiplication, transpose, etc.

Practice Exercises

  • Create a 3x3 matrix with numbers 1 to 9.
  • Access the center element of the matrix.
  • Transpose the matrix and print the result.
  • Find the sum of all rows and all columns.
  • Try matrix multiplication between two 2x2 matrices.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review