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')
t
... for which there are both matrix and dataframe methods. – Progeny