How to Transpose a Data Frame Using dplyr

Using the dplyr package in R, transposing a data frame is a simple task. All that needs to be done is to use the tibble::transpose() function on the data frame. This will switch the rows and columns of the data frame, allowing for a different view of the data. It is important to note that the column names will be used as the new row names and the original row names will be converted to columns. This is an efficient way to quickly and easily transform a data frame.


You can use the following basic syntax to transpose a data frame using the package in R:

library(dplyr)
library(tidyr)

df %>%
    pivot_wider(names_from = column1, values_from = column2)

The names_from argument specifies the values to use for the column names in the transposed data frame and the values_from argument specifies the cell values to use within the transposed data frame.

Note that the pipe operator (%>%) comes from the dplyr package while the pivot_wider() function comes from the tidyr package.

The following example shows how to use this syntax in practice.

Example: Transpose a Data Frame Using dplyr

Suppose we have the following data frame in R that contains information about various basketball teams:

#create data frame
df <- data.frame(team=c('Mavs', 'Nets', 'Kings', 'Lakers'),
                 points=c(99, 104, 119, 113))

#view data frame
df

    team points
1   Mavs     99
2   Nets    104
3  Kings    119
4 Lakers    113

Now suppose we would like to transpose the data frame so that the team names are used as column names and the points values are used as the cell values inside the data frame.

We can use the following syntax to do so:

library(dplyr)
library(tidyr)

#transpose data frame
df %>%
    pivot_wider(names_from = team, values_from = points)

# A tibble: 1 x 4
   Mavs  Nets Kings Lakers
      
1    99   104   119    113

The data frame has been transposed so that the team names are used as columns and the points values are used as cell values within the data frame.

Notice that the resulting data frame now contains 1 row and 4 columns.

Related:

The following tutorials explain how to perform other common tasks using dplyr:

x