Search code examples
rdata-munging

Pivot a character vector to a data.frame with specified number of columns


I have a vector of data where every 4th row starts a new observation. I need to pivot the data so that first four values become the first row, the next four values become the second, and so on.

Here is a simplified example...

Given the following data:

a <- rep(c("a", "b", "c", "d"), 3)

The desired output is:

  A_lab B_lab C_lab D_lab
1     a     b     c     d
2     a     b     c     d
3     a     b     c     d

Solution

  • If you want a matrix, just call:

    matrix(a, ncol=4, byrow=TRUE)
    
         [,1] [,2] [,3] [,4]
    [1,] "a"  "b"  "c"  "d" 
    [2,] "a"  "b"  "c"  "d" 
    [3,] "a"  "b"  "c"  "d"
    

    For a data.frame, pipe that result into data.frame:

    data.frame(matrix(a, ncol=4, byrow=TRUE))
    
      X1 X2 X3 X4
    1  a  b  c  d
    2  a  b  c  d
    3  a  b  c  d