How to Transpose a Data Frame in R?
Last Updated :
15 Jan, 2024
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
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:
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
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)
)
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
library (data.table)
cities_dt <- data.table (cities_data)
transposed_cities_dt <- transpose (cities_dt)
cat ( "Original Cities data.table:\n" )
print (cities_dt)
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
Share your thoughts in the comments
Please Login to comment...