In this article, we will discuss how to transpose dataframe in R Programming Language. Transposing means converting rows to columns and columns to rows
Creating Dataframe for demonstration:
R
data = data.frame (col1= c (1:5),
col2= c (6:10),
col3= c (11:15),
col4= c (16:20))
row.names (data) = c ( "r1" , "r2" , "r3" , "r4" , "r5" )
data
|
Output:
col1 col2 col3 col4
r1 1 6 11 16
r2 2 7 12 17
r3 3 8 13 18
r4 4 9 14 19
r5 5 10 15 20
Method 1: Using t() function
Here we are using t() function which stands for transpose to transpose a dataframe
Syntax: t(dataframe)
where dataframe is the input dataframe
Example:
R
data = data.frame (col1 = c (1:5),
col2 = c (6:10),
col3 = c (11:15),
col4 = c (16:20))
row.names (data) = c ( "r1" , "r2" , "r3" ,
"r4" , "r5" )
t (data)
|
Output:
r1 r2 r3 r4 r5
col1 1 2 3 4 5
col2 6 7 8 9 10
col3 11 12 13 14 15
col4 16 17 18 19 20
Method 2: Transpose Data Frame 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)
Example:
R
library (data.table)
data = data.frame (col1= c (1:5),
col2= c (6:10),
col3= c (11:15),
col4= c (16:20))
row.names (data) = c ( "r1" , "r2" , "r3" , "r4" , "r5" )
transpose (data)
|
Output:
V1 V2 V3 V4 V5
1 1 2 3 4 5
2 6 7 8 9 10
3 11 12 13 14 15
4 16 17 18 19 20