Transposing means converting rows to columns and columns to rows of a data frame. Transposing can be useful for various purposes, such as reshaping data or preparing it for specific analyses.
Transpose a Data Frame in R Using t() function
Here we are using t() function which stands for transpose to Transpose a Data Frame in R.
Syntax:
t(df)
Where :
- df is the input data frame
1. Creating a data frame for demonstration
We will create a sample data frame namedcities_data that contains information about four major U.S. cities. We are including columns for the city name, population in millions, area in square miles, and average income. We are then printing this data frame to display the structured information.
cities_data <- data.frame(
City = c("New York", "Los Angeles", "Chicago", "Houston"),
Population_Millions = c(8.4, 3.9, 2.7, 2.3),
Area_Square = c(468.9, 468.7, 227.3, 637.5),
Income = c(65300, 61700, 68000, 59500)
)
print(cities_data)
Output:

2. Transposing the Data Frame
We are transposing the cities_data data frame using thet() function, which switches rows and columns. We are effectively turning the cities into column headers and the attributes (Population, Area, Income) into rows for easier comparison across cities.
t(cities_data )
Output:

Transpose a Data Frame in R 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(df)
Where:
- df is the input dataframe
1. Loading the Required Library
We will install and load the data.table package, which provides tools for handling and transforming tabular data in R.
install.packages("data.table")
library(data.table)
2. Converting Data Frame to data.table
We are converting the existing cities_data data frame into a data.table object called cities_dt so that we can perform data operations using data.table features.
cities_dt <- data.table(cities_data)
3. Transposing the data.table
We are using the transpose() function to flip the rows and columns of cities_dt. This helps us view cities as columns and their attributes as rows for better comparative visualization.
transposed_cities_dt <- transpose(cities_dt)
4. Printing the Original data.table
We are printing the original cities_dt table to display the city-wise data in its standard format, where each row represents a city and columns hold attributes like population, area, and income.
cat("Original Cities data.table:\n")
print(cities_dt)
Output:

5. Printing the Transposed data.table
We are printing the transposed version of the data table so we can observe how the structure has changed (cities now become columns, and the attributes are presented as rows).
cat("\nTransposed Cities data.table:\n")
print(transposed_cities_dt)
Output:

In this article, we discussed how to Transpose a Data Frame in R Programming Language.