[R] Matrix transposition

Rui Barradas ruipbarradas at sapo.pt
Mon Apr 30 22:22:32 CEST 2012


Hello,


Filoche wrote
> 
> Hi everyone.
> 
> I want to transpose a data frame. Lets say the following DF:
> 
> df = data.frame(matrix(ncol=4, nrow = 10))
> 
> df[,1] = c(rep(1,5),rep(2,4), 3)
> df[,2] = c(rep('a',4),rep('b',3),rep('c',3))
> df[,3] = c(letters[c(5:13,13)])
> df[,4] = runif(10)
> 
> 
> 
> I would like to form a data frame with each line corresponding to colon X1
> and create a variable with columns X2 and X3.
> 
> This would give me a DF with the following columns.
> /
> *X1, ae, af, ag, bi, bj, bk, cl, cm,*
> /1 n n n n n NA NA NA NA NA
> 2 NA NA NA NA NA n n n n n 
> 3 NA NA NA NA NA NA NA NA NA n
> 
> where n = numbers in column X4.
> 
> I'm not sure how to manipulate my DF to rearrange it so I keep var X1 but
> I create 9 new variables with coloumns X2 and X3 with values from X4.
> 
> I hope I have been clear enough!
> 
> Thank in advance for your insights,
> Phil
> 


Try

library(reshape2)
x <- melt(df, c("X1", "X2", "X3"), "X4")
dcast(x, X1~X2+X3)

Then, you can change the colnames with 'sub' or 'gsub'.

Hope this helps,

Rui Barradas



--
View this message in context: http://r.789695.n4.nabble.com/Matrix-transposition-tp4599219p4599271.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list