Open In App

How to Transpose a Data Frame in R?

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to Transpose a Data Frame in R Programming Language. we use some methods to transpose a data frame.

What is Transpose?

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.

Creating a data frame for demonstration

R




# create a dataframe
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 the new DataFrame
print(cities_data)


Output:

         City Population_Millions Area_Square Income
1 New York 8.4 468.9 65300
2 Los Angeles 3.9 468.7 61700
3 Chicago 2.7 227.3 68000
4 Houston 2.3 637.5 59500

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(dataframe)

where dataframe is the input dataframe

R




# Creating another sample DataFrame
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)
)
 
# display transposed dataframe
t(cities_data )


Output:

                    [,1]       [,2]          [,3]      [,4]     
City "New York" "Los Angeles" "Chicago" "Houston"
Population_Millions "8.4" "3.9" "2.7" "2.3"
Area_Square "468.9" "468.7" "227.3" "637.5"
Income "65300" "61700" "68000" "59500"

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(dataframe)

R




# Load the data.table package
library(data.table)
 
# Convert the cities_data DataFrame to a data.table
cities_dt <- data.table(cities_data)
 
# Transpose the data.table
transposed_cities_dt <- transpose(cities_dt)
 
# Print the original data.table
cat("Original Cities data.table:\n")
print(cities_dt)
 
# Print the transposed data.table
cat("\nTransposed Cities data.table:\n")
print(transposed_cities_dt)


Output:

          City Population_Millions Area_Square Income
1: New York 8.4 468.9 65300
2: Los Angeles 3.9 468.7 61700
3: Chicago 2.7 227.3 68000
4: Houston 2.3 637.5 59500

Transposed Cities data.table:
V1 V2 V3 V4
1: New York Los Angeles Chicago Houston
2: 8.4 3.9 2.7 2.3
3: 468.9 468.7 227.3 637.5
4: 65300 61700 68000 59500


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads