简体   繁体   中英

Need to convert columns to rows in R

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM