transpose a dataframe in r

To transpose a dataframe in R, you can use the t() function or the transpose() function from the data.table package.

Here's an example of using the t() function to transpose a dataframe:

main.r
my_df <- data.frame(x = 1:3, y = 4:6, z = 7:9)
t(my_df)
56 chars
3 lines

This will return:

main.r
  [,1] [,2] [,3]
x    1    2    3
y    4    5    6
z    7    8    9
68 chars
5 lines

If you're working with larger datasets in R, you may want to use the transpose() function from the data.table package for improved performance. Here's an example:

main.r
library(data.table)
my_df <- data.frame(x = 1:3, y = 4:6, z = 7:9)
transpose(setDT(my_df))
91 chars
4 lines

This will also return:

main.r
      x y z
 [1,] 1 4 7
 [2,] 2 5 8
 [3,] 3 6 9
48 chars
5 lines

Note that when using transpose() from data.table, you must first convert your dataframe to a data.table object using the setDT() function.

gistlibby LogSnag