How to Transpose a DataFrame in R

To transpose a DataFarme in R using the t() function:

transposed_df <- t(df)

Example of Transposing a DataFrame in R

Given the following DataFrame in R:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

print(df)

The current DataFrame:

   product  price  brand
1 computer    800      A
2  monitor    450      B
3 keyboard    100      C
4  printer    150      X
5   tablet    300      Y

Transpose the DataFrame using the t() function:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

transposed_df <- t(df)

print(transposed_df)

The transposed DataFrame:

         [,1]        [,2]       [,3]        [,4]       [,5]    
product  "computer"  "monitor"  "keyboard"  "printer"  "tablet"
price    "800"       "450"      "100"       "150"      "300"   
brand    "A"         "B"        "C"         "X"        "Y" 

Leave a Comment