Try this also: reshape(cbind(Id = 1:8, DF), v.names = 'y', timevar = 'z', direction = 'wide', idvar = 'Id')[-1]
On Thu, Feb 25, 2010 at 10:17 AM, Juliet Ndukum <jpnts...@yahoo.com> wrote: > I have a matrix, called data. I used the code below to rearrange the data > such that the first column remains the same, but the y value falls under > either columns 2, 3 or 4, depending on the value of z. If z=1 for example, > then the value of y will fall under column 2, if z=2, the value of y falls > under column 3, and so on. > > data > x y z > [1,] 50 13 1 > [2,] 14 8 2 > [3,] 3 7 3 > [4,] 4 16 1 > [5,] 6 8 2 > [6,] 10 2 3 > [7,] 15 11 1 > [8,] 14 9 3 >> data1 <- data.frame(matrix(0, length(x), ncol(data)+1)) >> colnames(data1) <- c("x","y1","y2","y3") >> data1$x <- data[,1] >> data1$y1 <- apply(data, 1, function(x) (ifelse(x[3]==1,x[2],NA))) >> data1$y2 <- apply(data, 1, function(x) (ifelse(x[3]==2,x[2],NA))) >> data1$y3 <- apply(data, 1, function(x) (ifelse(x[3]==3,x[2],NA))) >> data1 > x y1 y2 y3 > 1 50 13 NA NA > 2 14 NA 8 NA > 3 3 NA NA 7 > 4 4 16 NA NA > 5 6 NA 8 NA > 6 10 NA NA 2 > 7 15 11 NA NA > 8 14 NA NA 9 > > I used the apply function (three times) to generate the output below, which > is as I wish to have it. > Can any one write for me a for loop that would produce the same results. > > Thanks in advance. > JN > > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.