0Pricing
R Academy · Lesson

Transposing and Reshaping Matrices

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

Transposing and Reshaping Matrices is a free R Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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))

Reshaping with dim(m) <- c(r, c)

You can reshape a matrix by reassigning its dim attribute. The total number of elements must stay the same. Reshaping reads and fills column by column, just like matrix().

m <- matrix(1:12, nrow = 3, ncol = 4)
cat('Original (3x4):
'); print(m)

# Reshape to 4x3
dim(m) <- c(4, 3)
cat('Reshaped to (4x3):
'); print(m)

# Reshape to 6x2
dim(m) <- c(6, 2)
cat('Reshaped to (6x2):
'); print(m)

Converting Matrix to Vector with as.vector()

as.vector(m) flattens a matrix into a one-dimensional vector, reading values column by column. This removes all dimension attributes from the object.

m <- matrix(c(10,20,30,40,50,60), nrow = 2, ncol = 3)
cat('Matrix:
'); print(m)

v <- as.vector(m)
cat('As vector (col-by-col):', v, '
')
cat('Is vector:', is.vector(v), '
')
cat('Is matrix:', is.matrix(v), '
')

Converting Vector to Matrix with as.matrix()

as.matrix(v) converts a vector into a single-column matrix. This is the simplest conversion. You can then reshape it using dim() to get the desired dimensions.

v <- c(5, 10, 15, 20, 25, 30)
cat('Vector:', v, '
')

# as.matrix makes a 6x1 matrix
m_single_col <- as.matrix(v)
cat('Single-column matrix:
'); print(m_single_col)
cat('Dimensions:', dim(m_single_col), '
')

rbind() — Stacking Rows

rbind() combines matrices or vectors by stacking rows. All inputs must have the same number of columns. The resulting matrix has the combined number of rows.

first_half <- matrix(1:6, nrow = 2, ncol = 3)
second_half <- matrix(7:12, nrow = 2, ncol = 3)

combined <- rbind(first_half, second_half)
cat('rbind result (4x3):
'); print(combined)
cat('Dimensions:', dim(combined), '
')

cbind() — Joining Columns

cbind() combines matrices or vectors by joining columns side by side. All inputs must have the same number of rows. The result has the combined number of columns.

ids <- matrix(101:104, nrow = 4, ncol = 1)
scores_mat <- matrix(c(88,79,95,72, 92,85,78,90), nrow = 4)

full_data <- cbind(ids, scores_mat)
colnames(full_data) <- c('ID', 'Test1', 'Test2')
cat('cbind result:
'); print(full_data)

rbind() and cbind() with Named Rows/Cols

When you rbind() or cbind() named matrices or named vectors, the dimension names are preserved (and in the case of vectors, the vector names become row or column names).

# Add a new student row with rbind
existing <- matrix(c(88,92,75, 79,85,90), nrow = 2, byrow = TRUE,
                   dimnames = list(c('Alice','Bob'), c('Math','Sci','Eng')))
new_student <- c(Math=95, Sci=78, Eng=82)
updated <- rbind(existing, Carol = new_student)
cat('Updated roster:
'); print(updated)

Double Transpose Identity

Applying t() twice returns the original matrix. This is a useful sanity check and demonstrates that transposition is its own inverse operation: t(t(m)) == m.

m <- matrix(c(1,2,3,4,5,6), nrow = 2)
cat('Original:
'); print(m)
cat('t(m):
');    print(t(m))
cat('t(t(m)):
'); print(t(t(m)))
cat('t(t(m)) == m:', all(t(t(m)) == m), '
')

Practical: Pivot-Style Reshape

A common reshaping task is converting between wide and long formats. Here we simulate a manual wide-to-long pivot using matrix operations — transposing, flattening, and rebuilding structure.

# Wide: 3 students x 4 months scores
wide <- matrix(c(85,88,90,92, 78,80,79,83, 91,94,88,95),
               nrow = 3, byrow = TRUE)
rownames(wide) <- c('Alice', 'Bob', 'Carol')
colnames(wide) <- c('Jan', 'Feb', 'Mar', 'Apr')
cat('Wide format:
'); print(wide)

# Transposed: 4 months x 3 students
long_view <- t(wide)
cat('Transposed (months x students):
'); print(long_view)

Reshape and Combine Summary

Key reshaping and combination tools for matrices:

  • t(m) — transpose (swap rows and columns)
  • dim(m) <- c(r, c) — reshape in place (same total elements)
  • as.vector(m) — flatten to 1D vector (column-major)
  • as.matrix(v) — convert vector to column matrix
  • rbind(...) — stack matrices vertically
  • cbind(...) — join matrices horizontally
# Demo all tools
v <- 1:6
m1 <- as.matrix(v)               # 6x1
dim(m1) <- c(2, 3)               # reshape to 2x3
m2 <- t(m1)                      # 3x2
m3 <- cbind(m2, c(10, 20, 30))   # 3x3
cat('Final matrix:
'); print(m3)

Quick Check

What dimensions does t(matrix(1:12, nrow = 3, ncol = 4)) produce?

Recap: Transposing and Reshaping

Excellent! Key takeaways from this lesson:

  • t(m) swaps rows and columns; t(t(m)) returns the original
  • dim(m) <- c(r, c) reshapes without copying (same number of elements required)
  • as.vector() flattens column-by-column; as.matrix() makes a single-column matrix
  • rbind() stacks rows (same column count required)
  • cbind() joins columns side by side (same row count required)
  • Named dimensions are preserved through these operations
# Practical: merge data then compute column means
team_a <- matrix(c(82,78,91, 85,80,88), nrow = 2, byrow=TRUE)
team_b <- matrix(c(75,92,79, 88,84,93), nrow = 2, byrow=TRUE)
all_teams <- rbind(team_a, team_b)
colnames(all_teams) <- c('Speed', 'Accuracy', 'Strength')
cat('Combined teams:
'); print(all_teams)
cat('Average per skill:', colMeans(all_teams), '
')

Frequently asked questions

Is the “Transposing and Reshaping Matrices” lesson free?

Yes — the full text of “Transposing and Reshaping Matrices” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Transposing and Reshaping Matrices”?

Use t(), dim(), and reshape operations on matrices. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Transposing and Reshaping Matrices” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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