Need to convert columns to rows in R

Ishan Basu picture Ishan Basu · Dec 24, 2015 · Viewed 31.3k times · Source

I have data that looks like

a     b     c
1     5     4
3     6     1
2     5     3

I want to convert it to convert all the columns to rows and want an output like

r1       r2     r3     r4
a        1       3      2
b        5       6      5
c        4       1      3

Thanks in advance

Answer

akrun picture akrun · Dec 24, 2015

We can transpose the dataset and convert to data.frame with the first column as the row names.

m1 <- t(df1)
d2 <- data.frame(r1= row.names(m1), m1, row.names=NULL) 

EDIT: Included the row.names argument in the data.frame call (from @Richard Scriven's comment)

Or as @Ananda Mahto mentioned, we can use names(df1) to create the 'r1' column, thereby skipping the creation of an object in the global environment.

d2 <- data.frame(r1=names(df1), t(df1))

Or another option is melt/dcast. We convert the data.frame to matrix, melt to 'long' format and then dcast it to 'wide' format.

library(reshape2)
dcast(melt(as.matrix(df1)), Var2~paste0('r', Var1), value.var='value')