Converting rows into columns and columns into rows using R

Christopher Bottoms picture Christopher Bottoms · Feb 23, 2015 · Viewed 113.3k times · Source

I have a dataframe with unique row names and unique column names. I want to convert the rows into columns and column into rows.

For example, this code:

starting_df <- data.frame(row.names= c(LETTERS[1:4]),
                          a = c(1:4),
                          b = seq(0.02,0.08,by=0.02),
                          c = c("Aaaa","Bbbb","Cccc","Dddd")
                )

results in the following:

> starting_df
  a    b    c
A 1 0.02 Aaaa
B 2 0.04 Bbbb
C 3 0.06 Cccc
D 4 0.08 Dddd

I want to convert it into another data frame containing exactly the same data, except that what were formerly rows were now columns and vice versa:

> final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Answer

Christopher Bottoms picture Christopher Bottoms · Feb 23, 2015

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!