Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing a dataframe maintaining the first column as heading

I have a big dataframe, but small example would be like this:

mydf <- data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50)) 

I want to transpose the dataframe and maintain the column 1 (A) as column heading ( letter[1:10]) as variable names. The following are scratch trials of unsuccessful codes.

tmydf = data.frame(t(mydf)) names(tmydf) <- tmydf[1,] 

Thanks;

like image 645
jon Avatar asked Nov 01 '11 17:11

jon


People also ask

How do I transpose a Dataframe in R studio?

To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) . This will, as previously hinted, result in a new matrix that is obtained by exchanging the rows and columns.

How do you transpose a matrix in R?

Rotating or transposing R objects You can rotate the data. frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.


2 Answers

Here is one way

tmydf = setNames(data.frame(t(mydf[,-1])), mydf[,1]) 
like image 183
Ramnath Avatar answered Oct 05 '22 11:10

Ramnath


Something like this perhaps:

tmp <- as.data.frame(t(mydf[,-1])) > colnames(tmp) <- mydf$A > tmp     a  b  c  d  e  f  g  h  i  j M1 11 12 13 14 15 16 17 18 19 20 M2 31 32 33 34 35 36 37 38 39 40 M3 41 42 43 44 45 46 47 48 49 50 
like image 34
joran Avatar answered Oct 05 '22 11:10

joran