Need to convert columns to rows in R

37,677

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')
Share:
37,677
Ishan Basu
Author by

Ishan Basu

Knowledge of analytics, SAS, R, Qlikview, Excel and VBA

Updated on July 25, 2022

Comments

  • Ishan Basu
    Ishan Basu over 1 year

    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