Home » How to Transpose a Data Frame in R (With Examples)

How to Transpose a Data Frame in R (With Examples)

by Erma Khan

There are two common methods you can use to transpose a data frame in R:

Method 1: Use Base R

#transpose data frame
t(df)

Method 2: Use data.table

library(data.table)

#transpose data frame
df_t 

#redefine row and column names
rownames(df_t) 

The following examples show how to use each of these methods in practice.

Method 1: Transpose Data Frame Using Base R

Suppose we have the following data frame:

#create data frame
df frame(A = c(1, 2, 3, 4, 5),
                 B = c(6, 7, 8, 9, 10),
                 C = c(11, 12, 13, 14, 15))

#define row names
row.names(df) #view data frame
df

      A  B  C
One   1  6 11
Two   2  7 12
Three 3  8 13
Four  4  9 14
Five  5 10 15

We can use the t() function from base R to quickly transpose the data frame:

#transpose data frame
t(df)

  One Two Three Four Five
A   1   2     3    4    5
B   6   7     8    9   10
C  11  12    13   14   15

The rows and the columns are now switched.

Method 2: Transpose Data Frame Using data.table

Once again suppose we have the following data frame:

#create data frame
df frame(A = c(1, 2, 3, 4, 5),
                 B = c(6, 7, 8, 9, 10),
                 C = c(11, 12, 13, 14, 15))

#define row names
row.names(df) #view data frame
df

      A  B  C
One   1  6 11
Two   2  7 12
Three 3  8 13
Four  4  9 14
Five  5 10 15

We can use the transpose() function from the data.table package to quickly transpose the data frame:

library(data.table)

#transpose data frame
df_t #redefine row and column names
rownames(df_t) #display transposed data frame
df_t

  One Two Three Four Five
A   1   2     3    4    5
B   6   7     8    9   10
C  11  12    13   14   15

The result matches the transposed data frame from the previous example.

Note: The data.table method will be much faster than base R if you are working with an extremely large data frame.

Additional Resources

The following tutorials explain how to perform other common operations on data frames in R:

How to Apply Function to Each Row of Data Frame in R
How to Add an Empty Column to a Data Frame in R
How to Subset a Data Frame in R

Related Posts