Skip to content
Related Articles

Related Articles

How to Transpose a DataFrame in R?

View Discussion
Improve Article
Save Article
  • Last Updated : 19 Dec, 2021
View Discussion
Improve Article
Save Article

In this article, we will discuss how to transpose dataframe in R Programming Language. Transposing means converting rows to columns and columns to rows

Creating Dataframe for demonstration:

R




# create a dataframe
data = data.frame(col1=c(1:5),
                  col2=c(6:10),
                  col3=c(11:15),
                  col4=c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3","r4","r5")
  
# display
data


Output:

   col1 col2 col3 col4
r1    1    6   11   16
r2    2    7   12   17
r3    3    8   13   18
r4    4    9   14   19
r5    5   10   15   20

Method 1: Using t() function

Here we are using t() function which stands for transpose to transpose a dataframe

Syntax: t(dataframe)

where dataframe is the input dataframe

Example:

R




# create a dataframe
data = data.frame(col1 = c(1:5), 
                  col2 = c(6:10),
                  col3 = c(11:15),
                  col4 = c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3",
                    "r4","r5")
  
# display transposed dataframe
t(data)


Output:

    r1 r2 r3 r4 r5
col1  1  2  3  4  5
col2  6  7  8  9 10
col3 11 12 13 14 15
col4 16 17 18 19 20

Method 2: Transpose Data Frame Using data.table

Here we are using data.table data structure to transpose the dataframe, we are using transpose() method to do this

Syntax: transpose(dataframe)

Example:

R




# load module
library(data.table)
  
# create a dataframe
data = data.frame(col1=c(1:5),
                  col2=c(6:10),
                  col3=c(11:15),
                  col4=c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3","r4","r5")
  
# display transposed dataframe
# using data.table
transpose(data)


Output:

 V1 V2 V3 V4 V5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13 14 15
4 16 17 18 19 20

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!