Skip to main content
HomeTutorialsR Programming

How to Transpose a Matrix in R: A Quick Tutorial

Learn three methods to transpose a matrix in R in this quick tutorial
Apr 2024

Transposing matrices is a staple data manipulation task in the R programming environment. In this tutorial, I will guide you through how to effectively transpose matrices in R, showcasing several methods to accomplish this task. Let’s get started!

The Quick Answer: How to Transpose a Matrix in R

If you're in a hurry, here's the quickest way to transpose a matrix in R: use the t() function. The t() function is part of base R and provides an immediate way to transpose a matrix. Here's a simple example:

# Creating a sample matrix
my_matrix <- matrix(1:6, nrow = 2, ncol = 3)
print(my_matrix)
      [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
# Transposing the matrix
transposed_matrix <- t(my_matrix)
print(transposed_matrix)
      [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6

What is Transposing?

Transposing a matrix involves flipping its rows and columns, turning row data into column data, and vice versa. This operation is commonly used in data manipulation to restructure data sets, making them more suitable for specific analyses or visualizations. For instance, consider a matrix containing daily temperatures for different cities. Transposing this data frame would switch rows (days) with columns (cities), potentially simplifying further operations like plotting or statistical analysis.

Day

New York

Lost Angeles

Chicago

Day 1

22

25

18

Day 2

20

28

21

A sample weather dataset across 3 cities before transposing

City

Day 1

Day 2

New York

22

20

Los Angeles

25

28

Chicago

18

21

A sample weather dataset across 3 cities after transposing

Three Methods to Transpose a Matrix in R

Given our matrix of daily temperatures for different cities, let's explore how to transpose this matrix using various methods in R.

Method #1: How to Transpose a Matrix in R Using Base R

The most straightforward method to transpose a matrix in R is by using the base R t() function, as demonstrated earlier. It’s efficient and direct and a go-to option for quickly transposing matrices without additional packages.

# Assume that temparature_matrix is already predefined
print(temperature_matrix)

      New_York Los_Angeles Chicago
Day 1       22          20      25
Day 2       28          18      21
# Transpose temperature_matrix
transposed_matrix <- t(temperature_matrix)

print(transposed_matrix)

      New_York Los_Angeles Chicago
Day 1       22          20      25
Day 2       28          18      21

Method #2: Transposing a Matrix in R Using the tidyverse

The tidyverse is a robust set of tools in R that make working with data efficient and consistent. While the tidyverse is generally used with data frames, you can convert a matrix to a data frame and then use tidyr to "transpose" it by pivoting. This is especially useful if you are already using the tidyverse to analyze data.

library(tidyr)
library(dplyr)
library(tibble)

# Converting the matrix to a data frame for tidyverse manipulation
temperature_df <- as.data.frame(temperature_matrix)

# "Transposing" the matrix by converting to long then wide format
transposed_df <- temperature_df %>%
  rownames_to_column(var = "Day") %>%
  pivot_longer(-Day, names_to = "City", values_to = "Temperature") %>%
  pivot_wider(names_from = City, values_from = Temperature)

print(transposed_df)
# A tibble: 2 × 4
  Day   New_York Los_Angeles Chicago
  <chr>    <dbl>       <dbl>   <dbl>
1 Day 1       22          20      25
2 Day 2       28          18      21

Method #3: Transposing a Matrix in R Using data.table

Similar to the tidyverse approach, data.table can work with data frames or data tables. Here's how you might transpose a matrix by first converting it to a data table:

library(data.table)

# Converting the matrix to a data.table
temperature_dt <- as.data.table(temperature_matrix, keep.rownames = "Day")

# Transposing the matrix by melting and dcasting (similar to pivot_longer and pivot_wider)
transposed_dt <- melt(temperature_dt, id.vars = "Day") %>%
  dcast(variable ~ Day, value.var = "value")

print(transposed_dt)
      variable Day 1 Day 2
1:    New_York    22    28
2: Los_Angeles    20    18
3:     Chicago    25    21

Final Thoughts

Transposing matrices is a fundamental skill in R programming. Whether you work with base R, tidyr within the tidyverse, or the data.table package, R provides flexible options to suit your data needs. If you want to learn more, check out our Reshaping Data with tidyr in R Cheat Sheet, or better yet, get started with the Data Manipulation in R Skill Track.


Photo of Adel Nehme
Author
Adel Nehme

Adel is a Data Science educator, speaker, and Evangelist at DataCamp where he has released various courses and live training on data analysis, machine learning, and data engineering. He is passionate about spreading data skills and data literacy throughout organizations and the intersection of technology and society. He has an MSc in Data Science and Business Analytics. In his free time, you can find him hanging out with his cat Louis.

Topics

Continue Your R Journey Today!

Track

R Programming

22hrs hr
Level-up your R programming skills! Learn how to work with common data structures, optimize code, and write your own functions.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

R Correlation Tutorial

Get introduced to the basics of correlation in R: learn more about correlation coefficients, correlation matrices, plotting correlations, etc.
David Woods's photo

David Woods

18 min

tutorial

Matrices in R Tutorial

Learn all about R's matrix, naming rows and columns, accessing elements also with computation like addition, subtraction, multiplication, and division.

Olivia Smith

7 min

tutorial

Understanding Confusion Matrix in R

This tutorial takes course material from DataCamp's Machine Learning Toolbox course and allows you to practice confusion matrices in R.
Ryan Sheehy's photo

Ryan Sheehy

3 min

tutorial

Data Reshaping in R Tutorial

Learn about data reshaping in R, different functions like rbind(), cbind(), along with Melt(), Dcast(), and finally about the transpose function.

Olivia Smith

7 min

tutorial

Sorting Data in R

How to sort a data frame in R.
DataCamp Team's photo

DataCamp Team

2 min

tutorial

Sorting in R using order() Tutorial

In this tutorial, you'll learn about sorting using order(). We will cover how to sort vectors using different parameters, sorting dataframes, and more.

Olivia Smith

6 min

See MoreSee More