Need to convert columns to rows in R
Asked Answered
F

1

7

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

Fairish answered 24/12, 2015 at 5:30 Comment(2)
Hint: transpose of a matrix.Desmid
Hint: .................... t ... for which there are both matrix and dataframe methods.Progeny
E
11

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')
En answered 24/12, 2015 at 5:35 Comment(2)
Since the names of "df1" would become your "r1", you could skip the creation of m1.Bersagliere
Thanks a lot. This really helped.Fairish

© 2022 - 2024 — McMap. All rights reserved.