1 Goal


The goal of this tutorial is to learn how to transpose a dataframe. We will show two different ways to do it.


2 Reading the data


# Transposing is the act of interchanging rows by columns in a dataframe
# We are going to use a modified version of the iris dataframe
iris_df <- read.csv("iris_transpose.csv", header = TRUE, stringsAsFactors = FALSE)
head(iris_df)
##            X Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1     setosa        5.006       3.428        1.462       0.246
## 2 versicolor        5.936       2.770        4.260       1.326
## 3  virginica        6.588       2.974        5.552       2.026
# The first column is actually the row names
rownames(iris_df) <- iris_df$X
iris_df$X <- NULL
head(iris_df)
##            Sepal.Length Sepal.Width Petal.Length Petal.Width
## setosa            5.006       3.428        1.462       0.246
## versicolor        5.936       2.770        4.260       1.326
## virginica         6.588       2.974        5.552       2.026

3 Transposing the dataframe

3.1 Converting it into matrix


# We create a new dataframe using the transpose of a matrix
iris_transpose <- as.data.frame(t(as.matrix(iris_df)))
iris_transpose
##              setosa versicolor virginica
## Sepal.Length  5.006      5.936     6.588
## Sepal.Width   3.428      2.770     2.974
## Petal.Length  1.462      4.260     5.552
## Petal.Width   0.246      1.326     2.026

3.2 Using the data.table library


library(data.table)
iris_transpose <- transpose(iris_df)
iris_transpose
##      V1    V2    V3
## 1 5.006 5.936 6.588
## 2 3.428 2.770 2.974
## 3 1.462 4.260 5.552
## 4 0.246 1.326 2.026
# However we have to get back the row and col names
rownames(iris_transpose) <- colnames(iris_df)
colnames(iris_transpose) <- rownames(iris_df)
iris_transpose
##              setosa versicolor virginica
## Sepal.Length  5.006      5.936     6.588
## Sepal.Width   3.428      2.770     2.974
## Petal.Length  1.462      4.260     5.552
## Petal.Width   0.246      1.326     2.026

4 Conclusion


In this tutorial we have learnt how to transpose a dataframe in two different ways.