0Pricing
R Academy · Lesson

Transposing and Reshaping Matrices

Use t(), dim(), and reshape operations on matrices.

Transposing a Matrix with t()

t(m) transposes a matrix — it flips rows and columns so that row i becomes column i in the result. The dimensions swap: a 3x4 matrix becomes a 4x3 matrix after transposition.

m <- matrix(1:6, nrow = 2, ncol = 3)
cat('Original (2x3):
'); print(m)
cat('Transposed (3x2):
'); print(t(m))
cat('Original dim:', dim(m), '-> Transposed dim:', dim(t(m)), '
')

Transpose with Named Dimensions

When a matrix has row and column names, t() correctly swaps the names: row names become column names and vice versa. This keeps your data labelled after transposition.

scores <- matrix(
  c(88,92,75, 79,85,90),
  nrow = 2, byrow = TRUE,
  dimnames = list(c('Alice', 'Bob'), c('Math', 'Sci', 'Eng'))
)
cat('Original (students x subjects):
'); print(scores)
cat('Transposed (subjects x students):
'); print(t(scores))

All lessons in this course

  1. Creating Matrices with matrix()
  2. Matrix Indexing and Subsetting
  3. Matrix Arithmetic and Operations
  4. Transposing and Reshaping Matrices
← Back to R Academy