You can use the following basic syntax to transpose a data frame using the dplyr 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: An Introduction to the pivot_wider() Function in R
The following tutorials explain how to perform other common tasks using dplyr:
How to Filter Rows that Contain a Certain String Using dplyr
How to Calculate Relative Frequencies Using dplyr
How to Select the First Row by Group Using dplyr