[R] Breaking up a Row in R (transpose)

Petr Savicky savicky at cs.cas.cz
Fri May 4 22:42:40 CEST 2012


On Fri, May 04, 2012 at 11:11:47AM -0700, marc212 wrote:
> I have something like 28 rows and 6000 columns.  How would I configure this
> with for loops.

The transformation may be splitted into simpler pieces using a for
loop over the 28 rows. Try the following.

  orig <- rbind(
  "0"=c(5, 6, 6, 7, 7, 9),
  "1"=c(3, 4, 4, 3, 9, 9),
  "2"=c(5, 2, 6, 4, 7, 4))
  colnames(orig) <- rep(c("x", "y"), times=3)

  out <- matrix(nrow=ncol(orig)/2, ncol=2*nrow(orig))
  for (i in seq.int(length=nrow(orig))) {
      out[, 2*(i-1) + 1:2] <- matrix(orig[i, ], nrow=nrow(out), ncol=2, byrow=TRUE)
  }

  out

       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]    5    6    3    4    5    2
  [2,]    6    7    4    3    6    4
  [3,]    7    9    9    9    7    4

Hope this helps.

Petr Savicky.



More information about the R-help mailing list